DocXEncoder.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Export\Encoder;
  4. use App\Enum\Export\ExportFormatEnum;
  5. use App\Service\Utils\FileUtils;
  6. use Phpdocx\Create\CreateDocx;
  7. use Throwable;
  8. /**
  9. * Encode HTML to docx format.
  10. */
  11. class DocXEncoder implements EncoderInterface
  12. {
  13. public function __construct(
  14. private readonly CreateDocx $phpDocx,
  15. private readonly FileUtils $fileUtils
  16. ) {}
  17. public function support(string $format): bool
  18. {
  19. return $format === ExportFormatEnum::DOCX->value;
  20. }
  21. // TODO: resolve Phpstan errors
  22. /**
  23. * Encode the given HTML content into docX, and
  24. * return the encoded content.
  25. *
  26. * @param array<string, mixed> $options
  27. * @throws Throwable
  28. */
  29. public function encode(string $html, array $options = []): string
  30. {
  31. $tempFilename = $this->fileUtils->getTempFilename('docx');
  32. // @see https://www.phpdocx.com/documentation/introduction/html-to-word-PHP#
  33. $this->phpDocx->embedHTML($html);
  34. try {
  35. $this->phpDocx->createDocx($tempFilename);
  36. return file_get_contents($tempFilename);
  37. } catch (\Throwable $e) {
  38. if (is_file($tempFilename)) {
  39. unlink($tempFilename);
  40. }
  41. throw $e;
  42. }
  43. }
  44. }