Passed
Pull Request — master (#5)
by Carlos C
06:01 queued 02:12
created

Html2PdfBuilder   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 60.87%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 19
c 2
b 0
f 0
dl 0
loc 56
ccs 14
cts 23
cp 0.6087
rs 10
wmc 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
A build() 0 3 1
A buildPdf() 0 5 1
A convertNodeToHtml() 0 3 1
A __construct() 0 9 2
A convertHtmlToPdf() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace PhpCfdi\CfdiToPdf\Builders;
6
7
use PhpCfdi\CfdiToPdf\Builders\HtmlTranslators\HtmlTranslatorInterface;
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
    /** @var HtmlTranslators\HtmlTranslatorInterface */
16
    private $htmlTranslator;
17
18
    /**
19
     * Html2PdfBuilder constructor.
20
     *
21
     * @param HtmlTranslatorInterface|null $htmlTranslator If NULL will use a generic translator
22
     */
23 3
    public function __construct(HtmlTranslatorInterface $htmlTranslator = null)
24
    {
25 3
        if (null === $htmlTranslator) {
26 3
            $htmlTranslator = new HtmlTranslators\PlatesHtmlTranslator(
27 3
                dirname(__DIR__, 2) . '/templates/', // __DIR__ is src/Builders
28 3
                'generic'
29
            );
30
        }
31 3
        $this->htmlTranslator = $htmlTranslator;
32 3
    }
33
34 1
    public function build(CfdiData $data, string $destination)
35
    {
36 1
        file_put_contents($destination, $this->buildPdf($data));
37 1
    }
38
39
    /**
40
     * Transforms CfdiData to Pdf string
41
     *
42
     * @param CfdiData $data
43
     * @return string
44
     */
45 1
    public function buildPdf(CfdiData $data): string
46
    {
47 1
        $html = $this->convertNodeToHtml($data);
48 1
        $output = $this->convertHtmlToPdf($html);
49 1
        return $output;
50
    }
51
52
    public function convertHtmlToPdf(string $html): string
53
    {
54
        // don't do it directly since Html2Pdf::output check that the file extension is pdf
55
        try {
56
            $html2Pdf = new Html2Pdf('P', 'Letter', 'es', true, 'UTF-8', [10, 10, 10, 10]);
57
            $html2Pdf->writeHTML($html);
58
            $output = $html2Pdf->output('', 'S');
59
            return $output;
60
        } catch (Html2PdfException $exception) {
61
            /** @codeCoverageIgnore don't know how to invoke this exception on Html2Pdf */
62
            throw new RuntimeException('Unable to convert CFDI', 0, $exception);
63
        }
64
    }
65
66
    public function convertNodeToHtml(CfdiData $cfdiData): string
67
    {
68
        return $this->htmlTranslator->translate($cfdiData);
69
    }
70
}
71