| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- <?php
- 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<string, mixed> $options
- * @throws Throwable
- */
- public function encode(string $html, array $options = []): string
- {
- $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;
- }
- }
- }
|