RprtCli/app/src/Utils/PdfExport/PdfExportService.php

104 lines
3.1 KiB
PHP
Raw Normal View History

2021-09-21 01:13:15 +02:00
<?php
declare(strict_types=1);
namespace RprtCli\Utils\PdfExport;
use Exception;
use RprtCli\Utils\Configuration\ConfigurationInterface;
use Mpdf\Output\Destination;
class PdfExportService implements PdfExportInterface {
protected $templatePath;
protected $output;
protected $config;
protected $mpdf;
public function __construct(ConfigurationInterface $config, $mpdf) {
$this->config = $config;
$this->mpdf = $mpdf;
}
public function getTemplatePath(): ?string
{
if (!isset($this->templatePath)) {
$template_path = $this->config->get('report.template_path', FALSE);
if (!$template_path) {
$template_path = readline('Enter template file path: ');
}
if (!file_exists($template_path)) {
throw new Exception('Template file not found!');
}
$this->templatePath = $template_path;
}
return $this->templatePath;
}
public function setTemplatePath(string $path): void {
if (file_exists($path)) {
$this->templatePath = $path;
return;
}
throw new Exception('Template file not found!');
}
public function parsedDataToHtmlTable(array $data): ?string {
$table = '<table><thead><tr>';
$header = array_shift($data);
foreach ($header as $cell) {
$table .= "<th>{$cell}</th>";
}
$table .= '</tr></thead><tbody>';
foreach ($data as $row) {
$cells = [];
foreach ($row as $cell) {
$cells[] = "<td>{$cell}</td>";
}
$rows[] = '<tr>' . implode($cells) . '</tr>';
}
$table .= implode('', $rows);
$table .= '</tbody></table>';
return $table;
}
public function replaceTokensInTemplate(string $template_path, array $tokens): ?string
{
$template = file_get_contents($template_path);
foreach ($tokens as $key => $value) {
$template = str_replace("[[{$key}]]", $value, $template);
}
return $template;
}
public function pdfExport(string $html, $output = null): bool {
$this->mpdf->SetProtection(array('print'));
$this->mpdf->SetTitle("Acme Trading Co. - Invoice");
$this->mpdf->SetAuthor("Acme Trading Co.");
$this->mpdf->SetDisplayMode('fullpage');
$this->mpdf->WriteHTML($html);
if (!$this->output) {
$this->output = $this->config->get('report.output', NULL) ?? readline('Enter output file path: ');
}
$this->mpdf->Output($this->output, Destination::FILE);
return file_exists($this->output);
}
public function setOutput(string $path) {
$this->output = $path;
}
public function fromDataToPdf(array $data, array $tokens = []): bool {
$template_path = $this->getTemplatePath();
$tokens['table'] = $this->parsedDataToHtmlTable($data);
$html = $this->replaceTokensInTemplate($template_path, $tokens);
$success = $this->pdfExport($html);
return $success;
}
}