Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
28 / 28 |
|
100.00% |
3 / 3 |
CRAP | |
100.00% |
1 / 1 |
| DocumentPdfGenerator | |
100.00% |
28 / 28 |
|
100.00% |
3 / 3 |
4 | |
100.00% |
1 / 1 |
| disk | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| generate | |
100.00% |
24 / 24 |
|
100.00% |
1 / 1 |
2 | |||
| qrSvg | |
100.00% |
3 / 3 |
|
100.00% |
1 / 1 |
1 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace ImovelZapAi\Documents\Application\Services; |
| 6 | |
| 7 | use BaconQrCode\Renderer\Image\SvgImageBackEnd; |
| 8 | use BaconQrCode\Renderer\ImageRenderer; |
| 9 | use BaconQrCode\Renderer\RendererStyle\RendererStyle; |
| 10 | use BaconQrCode\Writer; |
| 11 | use Dompdf\Dompdf; |
| 12 | use Dompdf\Options; |
| 13 | use Illuminate\Support\Facades\Storage; |
| 14 | use ImovelZapAi\Documents\Infrastructure\Persistence\Eloquent\BusinessDocumentModel; |
| 15 | use ImovelZapAi\Documents\Infrastructure\Persistence\Eloquent\DocumentVersionModel; |
| 16 | |
| 17 | final class DocumentPdfGenerator |
| 18 | { |
| 19 | public function disk(): string |
| 20 | { |
| 21 | return (string) config('documents.disk', 'local'); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @return array{disk: string, path: string} |
| 26 | */ |
| 27 | public function generate(BusinessDocumentModel $document, DocumentVersionModel $version, string $publicUrl): array |
| 28 | { |
| 29 | $qrSvg = $this->qrSvg($publicUrl !== '' ? $publicUrl : $version->validation_code); |
| 30 | $html = view('documents.pdf', [ |
| 31 | 'document' => $document, |
| 32 | 'version' => $version, |
| 33 | 'qrSvg' => $qrSvg, |
| 34 | 'company' => $version->snapshot['company_name'] ?? '', |
| 35 | 'body' => $version->html_body, |
| 36 | ])->render(); |
| 37 | |
| 38 | $options = new Options; |
| 39 | $options->set('isRemoteEnabled', true); |
| 40 | $options->set('defaultFont', 'DejaVu Sans'); |
| 41 | $dompdf = new Dompdf($options); |
| 42 | $dompdf->loadHtml($html); |
| 43 | $dompdf->setPaper('A4'); |
| 44 | $dompdf->render(); |
| 45 | |
| 46 | $path = sprintf( |
| 47 | 'documents/%s/%s/v%s-%s.pdf', |
| 48 | $document->tenant_id, |
| 49 | $document->id, |
| 50 | $version->version, |
| 51 | $version->validation_code, |
| 52 | ); |
| 53 | |
| 54 | Storage::disk($this->disk())->put($path, $dompdf->output()); |
| 55 | |
| 56 | return ['disk' => $this->disk(), 'path' => $path]; |
| 57 | } |
| 58 | |
| 59 | private function qrSvg(string $payload): string |
| 60 | { |
| 61 | $renderer = new ImageRenderer(new RendererStyle(120), new SvgImageBackEnd); |
| 62 | $writer = new Writer($renderer); |
| 63 | |
| 64 | return $writer->writeString($payload); |
| 65 | } |
| 66 | } |