Test Setup Failed
Push — master ( 8889c2...0ccb08 )
by Bingo
08:33
created

QrCodeRenderer   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 18
c 1
b 0
f 1
dl 0
loc 31
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 22 1
A __construct() 0 3 1
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
    public function __construct(PhpDocxTemplate $template)
15
    {
16
        $this->template = $template;
17
    }
18
19
    public function render(string $url, int $size = 100, int $margin = 10): string
20
    {
21
        $qrCode = new QrCode($url);
22
        $qrCode->setSize($size);
23
        $qrCode->setMargin($margin);
24
        $writer = new PngWriter();
25
        $result = $writer->write($qrCode);
26
        $path = sys_get_temp_dir() . "/" . uniqid("", true) . ".png";
27
        $result->saveToFile($path);
28
29
        $docx = $this->template->getDocx();
30
        $preparedImageAttrs = $docx->prepareImageAttrs(['path' => $path, 'width' => $size, 'height' => $size]);
31
        $imgPath = $preparedImageAttrs['src'];
32
33
        // get image index
34
        $imgIndex = $docx->getNextRelationsIndex($docx->getMainPartName());
35
        $rid = 'rId' . $imgIndex;
36
37
        // replace preparations
38
        $docx->addImageToRelations($docx->getMainPartName(), $rid, $imgPath, $preparedImageAttrs['mime']);
39
        $xmlImage = str_replace(array('{RID}', '{WIDTH}', '{HEIGHT}'), array($rid, $preparedImageAttrs['width'], $preparedImageAttrs['height']), $docx->getImageTemplate());
40
        return $xmlImage;
41
    }
42
}
43