Completed
Push — master ( a35e81...521884 )
by Carlos C
03:49 queued 10s
created

Html2PdfBuilder   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Test Coverage

Coverage 88.24%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 14
c 2
b 0
f 0
dl 0
loc 39
ccs 15
cts 17
cp 0.8824
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 3 1
A buildPdf() 0 5 1
A convertNodeToHtml() 0 5 1
A convertHtmlToPdf() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\CfdiToPdf\Builders;
6
7
use League\Plates\Engine as PlatesEngine;
8
use PhpCfdi\CfdiToPdf\CfdiData;
9
use RuntimeException;
10
use Spipu\Html2Pdf\Exception\Html2PdfException;
11
use Spipu\Html2Pdf\Html2Pdf;
12
13
class Html2PdfBuilder implements BuilderInterface
14
{
15 2
    public function build(CfdiData $data, string $destination)
16
    {
17 2
        file_put_contents($destination, $this->buildPdf($data));
18 2
    }
19
20
    /**
21
     * Transforms CfdiData to Pdf string
22
     *
23
     * @param CfdiData $data
24
     * @return string
25
     */
26 2
    public function buildPdf(CfdiData $data): string
27
    {
28 2
        $html = $this->convertNodeToHtml($data);
29 2
        $output = $this->convertHtmlToPdf($html);
30 2
        return $output;
31
    }
32
33 1
    public function convertHtmlToPdf(string $html): string
34
    {
35
        // don't do it directly since Html2Pdf::output check that the file extension is pdf
36
        try {
37 1
            $html2Pdf = new Html2Pdf('P', 'Letter', 'es', true, 'UTF-8', [10, 10, 10, 10]);
38 1
            $html2Pdf->writeHTML($html);
39 1
            $output = $html2Pdf->output('', 'S');
40 1
            return $output;
41
        } catch (Html2PdfException $exception) {
42
            /** @codeCoverageIgnore don't know how to invoke this exception on Html2Pdf */
43
            throw new RuntimeException('Unable to convert CFDI', 0, $exception);
44
        }
45
    }
46
47 1
    public function convertNodeToHtml(CfdiData $cfdiData): string
48
    {
49
        // __DIR__ is src/Builders
50 1
        $plates = new PlatesEngine(dirname(__DIR__, 2) . '/templates/');
51 1
        return $plates->render('generic', ['cfdiData' => $cfdiData]);
52
    }
53
}
54