DompdfDriver::convertCurrencies()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 12
ccs 5
cts 5
cp 1
rs 10
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Traincase\HtmlToPdfTinker\Drivers;
4
5
use Dompdf\Dompdf;
6
use Dompdf\Options;
7
use League\Flysystem\Filesystem;
8
use Traincase\HtmlToPdfTinker\DTO\PdfToGenerateDTO;
9
use Traincase\HtmlToPdfTinker\Exceptions\PdfCouldNotBeCreatedException;
10
11
class DompdfDriver extends Driver
12
{
13
    private Dompdf $domPdf;
14
15 3
    public function __construct(Dompdf $dompdf)
16
    {
17 3
        $this->domPdf = $dompdf;
18
    }
19
20
    /**
21
     * Create the PDF and return it in string format.
22
     *
23
     * @param Filesystem $filesystem Filesystem used for storing the PDF
24
     * @param PdfToGenerateDTO $dto Data needed to generate the PDF file
25
     * @return string Filepath to the generated PDF file
26
     * @throws PdfCouldNotBeCreatedException
27
     */
28 3
    public function storeOnFilesystem(Filesystem $filesystem, PdfToGenerateDTO $dto): string
29
    {
30
        try {
31 3
            $this->domPdf->setPaper('a4', $dto->orientation);
32 3
            $this->domPdf->setOptions(new Options($dto->options));
33 3
            $this->domPdf->loadHTML($this->convertCurrencies($dto->html));
34 3
            $this->domPdf->render();
35
36 3
            $pdf = $this->domPdf->output();
37
38 3
            if (!$pdf) {
39 1
                throw new \Exception('Dompdf could not create PDF');
40
            }
41
42 2
            $fullPath = $this->getFullPath($dto->path, $dto->filename);
43
44 2
            $filesystem->write($this->getFullPath($dto->path, $dto->filename), $pdf);
45
46 1
            return $fullPath;
47 2
        } catch (\Exception $e) {
48 2
            throw new PdfCouldNotBeCreatedException('Dompdf could not create PDF', $e->getCode(), $e);
49
        }
50
    }
51
52
    /**
53
     * @param string $html
54
     * @return string|string[]
55
     */
56 3
    private function convertCurrencies(string $html): string
57
    {
58 3
        $replacers = array(
59
            '€' => '&#0128;',
60
            '£' => '&pound;',
61
        );
62
63 3
        foreach ($replacers as $search => $replace) {
64 3
            $html = str_replace($search, $replace, $html);
65
        }
66
67 3
        return $html;
68
    }
69
}
70