QrCodeRenderer::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
namespace PhpDocxTemplate\Twig\Impl;
4
5
use Endroid\QrCode\QrCode;
6
use Endroid\QrCode\Writer\PngWriter;
7
use PhpDocxTemplate\PhpDocxTemplate;
8
use PhpDocxTemplate\Twig\RendererInterface;
9
10
class QrCodeRenderer implements RendererInterface
11
{
12
    private $template;
13
14 8
    public function __construct(PhpDocxTemplate $template)
15
    {
16 8
        $this->template = $template;
17 8
    }
18
19 1
    public function render(string $url, int $size = 100, int $margin = 10, string $unit = 'px'): string
20
    {
21 1
        $qrCode = new QrCode($url);
22 1
        $qrCode->setSize($size);
23 1
        $qrCode->setMargin($margin);
24 1
        $writer = new PngWriter();
25 1
        $result = $writer->write($qrCode);
26 1
        $path = sys_get_temp_dir() . "/" . uniqid("", true) . ".png";
27 1
        $result->saveToFile($path);
28
29 1
        $docx = $this->template->getDocx();
30 1
        $preparedImageAttrs = $docx->prepareImageAttrs(['path' => $path, 'width' => $size, 'height' => $size, 'unit' => $unit]);
31 1
        $imgPath = $preparedImageAttrs['src'];
32
33
        // get image index
34 1
        $imgIndex = $docx->getNextRelationsIndex($docx->getMainPartName());
35 1
        $rid = 'rId' . $imgIndex;
36
37
        // replace preparations
38 1
        $docx->addImageToRelations($docx->getMainPartName(), $rid, $imgPath, $preparedImageAttrs['mime']);
39 1
        $xmlImage = str_replace(array('{IMAGEID}', '{WIDTH}', '{HEIGHT}'), array($imgIndex, $preparedImageAttrs['width'], $preparedImageAttrs['height']), $docx->getImageTemplate());
40 1
        return $xmlImage;
41
    }
42
}
43