Browse Source

cleanup code and complete DocxEncoder

Olivier Massot 1 year ago
parent
commit
049dcbe62d

+ 25 - 9
src/Service/Export/Encoder/DocXEncoder.php

@@ -5,34 +5,50 @@ declare(strict_types=1);
 namespace App\Service\Export\Encoder;
 
 use App\Enum\Export\ExportFormatEnum;
+use App\Service\Utils\FileUtils;
 use Phpdocx\Create\CreateDocx;
+use Throwable;
 
 /**
  * Encode HTML to docx format.
  */
 class DocXEncoder implements EncoderInterface
 {
+    public function __construct(
+        private readonly CreateDocx $phpDocx,
+        private readonly FileUtils $fileUtils
+    ) {}
+
     public function support(string $format): bool
     {
         return $format === ExportFormatEnum::DOCX->value;
     }
 
     //  TODO: resolve Phpstan errors
+
     /**
      * Encode the given HTML content into docX, and
      * return the encoded content.
      *
-     * @param array<mixed> $options
+     * @param array<string, mixed> $options
+     * @throws Throwable
      */
     public function encode(string $html, array $options = []): string
     {
-        //    $docx = new CreateDocx();
-        //    $docx->embedHTML($html);
-        //    $tempFile = tempnam(sys_get_temp_dir(), 'docx');
-        //    $docx->createDocx($tempFile);
-        //    $content = file_get_contents($tempFile);
-        //    unlink($tempFile);
-        //    return $content;
-        return '';
+        $tempFilename = $this->fileUtils->getTempFilename('docx');
+
+        // @see https://www.phpdocx.com/documentation/introduction/html-to-word-PHP#
+        $this->phpDocx->embedHTML($html);
+
+        try {
+            $this->phpDocx->createDocx($tempFilename);
+
+            return file_get_contents($tempFilename);
+        } catch (\Throwable $e) {
+            if (is_file($tempFilename)) {
+                unlink($tempFilename);
+            }
+            throw $e;
+        }
     }
 }

+ 19 - 53
src/Service/Export/Encoder/PdfEncoder.php

@@ -21,62 +21,28 @@ class PdfEncoder implements EncoderInterface
         return $format === ExportFormatEnum::PDF->value;
     }
 
+    /**
+     * Converts the provided HTML content into a PDF document.
+     *
+     * @param string $html The HTML content to be converted to PDF.
+     * @param array<string, mixed> $options Optional configuration settings for the PDF generation
+     *                                      @see https://github.com/dompdf/dompdf/blob/master/src/Options.php
+     *
+     * @return string The generated PDF content as a string.
+     */
     public function encode(string $html, array $options = []): string
     {
-        $options = new Options();
-        $options->setIsRemoteEnabled(true);
-        $options->setChroot(Path::getProjectDir() . '/public');
-        $options->setIsRemoteEnabled(true);
-
-        $dompdf = new Dompdf($options);
-        $dompdf->setPaper('A4', 'portrait');
+        $defaultOptions = new Options();
+        $defaultOptions->setIsRemoteEnabled(true);
+        $defaultOptions->setChroot(Path::getProjectDir() . '/public');
+        $defaultOptions->setIsRemoteEnabled(true);
+        $defaultOptions->setDefaultPaperOrientation('portrait');
+        $defaultOptions->setDefaultPaperSize('A4');
+        $defaultOptions->set($options);
+
+        $dompdf = new Dompdf($defaultOptions);
         $dompdf->loadHtml($html);
         $dompdf->render();
-        $pdfContent = $dompdf->output();
-
-        return $pdfContent;
-
-//        $tempDir = Path::getProjectDir() . '/var/tmp';
-//        if (!is_dir($tempDir)) {
-//            mkdir($tempDir);
-//        }
-//
-//        $tempFileName = $tempDir . '/' . uniqid();
-//        $pfdFileName = $tempFileName . '.pdf';
-//        $docxFileName = $tempFileName . '.docx';
-//
-//        // @see https://www.phpdocx.com/documentation/introduction/html-to-word-PHP#
-//        $this->phpDocx->modifyPageLayout('A4', ['marginRight' => 800, 'marginLeft' => 800]);
-//        $this->phpDocx->embedHTML($html);
-//        $this->phpDocx->createDocx($docxFileName);
-//
-//        die;
-//        $options = new Options();
-//        $options->setIsRemoteEnabled(true);
-//        $options->setChroot(Path::getProjectDir() . '/public');
-//
-//        $dompdf = new Dompdf($options);
-//
-//        // @see https://www.phpdocx.com/documentation/introduction/pdf-conversion-plugin-installation-guide
-//        $this->phpDocx->transformDocument(
-//            $docxFileName,
-//            $pfdFileName,
-//            'native',
-//            ['dompdf' => $dompdf]
-//        );
-//
-//        $pdfContent = file_get_contents($pfdFileName);
-//        if ($pdfContent === false) {
-//            throw new \RuntimeException('Pdf file can not be read.');
-//        }
-//
-////        if (!unlink($docxFileName)) {
-////            throw new \RuntimeException('Temp file can not be deleted.');
-////        }
-//        if (!unlink($pfdFileName)) {
-//            throw new \RuntimeException('Temp file can not be deleted.');
-//        }
-//
-//        return $pdfContent;
+        return $dompdf->output();
     }
 }

+ 23 - 0
src/Service/Utils/FileUtils.php

@@ -5,7 +5,9 @@ declare(strict_types=1);
 namespace App\Service\Utils;
 
 use App\Entity\Core\File;
+use Exception;
 use Mimey\MimeTypes;
+use RuntimeException;
 
 class FileUtils
 {
@@ -45,4 +47,25 @@ class FileUtils
 
         return boolval(preg_match('#^image#', $mimetype));
     }
+
+    /**
+     * Génère un nom de fichier temporaire situé dans le répertoire var/tmp,
+     * avec l'extension et le préfixe donnés.
+     *
+     * @param string $ext
+     * @param string $prefix
+     * @return string
+     * @throws RuntimeException
+     */
+    public function getTempFilename(string $ext = 'tmp', string $prefix = ''): string
+    {
+        if (empty($ext)) {
+            throw new RuntimeException('Extension can not be empty');
+        }
+        $tempDir = Path::getProjectDir() . '/var/tmp';
+        if (!is_dir($tempDir)) {
+            mkdir($tempDir);
+        }
+        return $tempDir . '/' . $prefix . uniqid() . '.' . $ext;
+    }
 }