|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace KNPLabs\Snappy\Core\Frontend; |
| 6 | + |
| 7 | +use KNPLabs\Snappy\Core\Backend\Adapter; |
| 8 | +use KNPLabs\Snappy\Core\Backend\Options; |
| 9 | +use KNPLabs\Snappy\Core\Exception\DOMDocumentException; |
| 10 | +use KNPLabs\Snappy\Core\Exception\FrontendUnsupportedBackendException; |
| 11 | +use KNPLabs\Snappy\Core\Filesystem\SplResourceInfo; |
| 12 | +use Psr\Http\Message\StreamFactoryInterface; |
| 13 | +use Psr\Http\Message\StreamInterface; |
| 14 | + |
| 15 | +final class DOMDocumentToPdf implements Adapter\DOMDocumentToPdf |
| 16 | +{ |
| 17 | + public function __construct(private readonly Adapter $adapter, private readonly StreamFactoryInterface $streamFactory) {} |
| 18 | + |
| 19 | + public function withOptions(callable|Options $options): static |
| 20 | + { |
| 21 | + return new self( |
| 22 | + $this->adapter->withOptions($options), |
| 23 | + $this->streamFactory, |
| 24 | + ); |
| 25 | + } |
| 26 | + |
| 27 | + public function generateFromDOMDocument(\DOMDocument $document): StreamInterface |
| 28 | + { |
| 29 | + if ($this->adapter instanceof Adapter\DOMDocumentToPdf) { |
| 30 | + return $this->adapter->generateFromDOMDocument($document); |
| 31 | + } |
| 32 | + |
| 33 | + $html = $document->saveHTML(); |
| 34 | + |
| 35 | + if (false === $html) { |
| 36 | + throw new DOMDocumentException('Unable to read HTML from DOMDocument.'); |
| 37 | + } |
| 38 | + |
| 39 | + if ($this->adapter instanceof Adapter\HtmlToPdf) { |
| 40 | + return $this->adapter->generateFromHtml($html); |
| 41 | + } |
| 42 | + |
| 43 | + if ($this->adapter instanceof Adapter\StreamToPdf) { |
| 44 | + return $this->adapter->generateFromStream( |
| 45 | + $this->streamFactory->createStream($html) |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + if ($this->adapter instanceof Adapter\HtmlFileToPdf) { |
| 50 | + $file = SplResourceInfo::fromTmpFile(); |
| 51 | + |
| 52 | + fwrite($file->resource, $html); |
| 53 | + |
| 54 | + return $this->adapter->generateFromHtmlFile($file); |
| 55 | + } |
| 56 | + |
| 57 | + throw new FrontendUnsupportedBackendException( |
| 58 | + self::class, |
| 59 | + $this->adapter::class, |
| 60 | + ); |
| 61 | + } |
| 62 | +} |
0 commit comments