Passed
Pull Request — master (#52)
by Manuel
03:44
created

QrCode::writeDataUri()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sprain\SwissQrBill\QrCode;
4
5
use Endroid\QrCode\QrCode as BaseQrCode;
6
use Endroid\QrCode\QrCodeInterface;
7
use Sprain\SwissQrBill\QrCode\Exception\UnsupportedFileExtensionException;
8
9
class QrCode extends BaseQrCode implements QrCodeInterface
10
{
11
    const FILE_FORMAT_PNG = 'png';
12
    const FILE_FORMAT_SVG = 'svg';
13
14
    // A file extension is supported if the underlying library supports it,
15
    // including the possibility to add a logo in the center of the qr code.
16
    const SUPPORTED_FILE_FORMATS = [
17
        self::FILE_FORMAT_PNG,
18
        self::FILE_FORMAT_SVG
19
    ];
20
21
    private const SWISS_CROSS_LOGO_FILE_PNG = __DIR__ . '/../../assets/swiss-cross.png';
22
    private const SWISS_CROSS_LOGO_FILE_SVG = __DIR__ . '/../../assets/swiss-cross.svg';
23
24
    public function writeFile(string $path): void
25
    {
26
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
27
        $this->setWriterByExtension($extension);
28
29
        $this->addLogoInMatchingFileFormat();
30
31
        parent::writeFile($path);
32
    }
33
34
    public function writeDataUri(): string
35
    {
36
        $this->addLogoInMatchingFileFormat();
37
38
        return parent::writeDataUri();
39
    }
40
41
    public function setWriterByExtension(string $extension): void
42
    {
43
        if (!in_array($extension, self::SUPPORTED_FILE_FORMATS)) {
44
            throw new UnsupportedFileExtensionException(sprintf(
45
                'The qr code file cannot be created. Only these file extensions are supported: %s. You provided: %s.',
46
                implode(', ', self::SUPPORTED_FILE_FORMATS),
47
                $extension
48
            ));
49
        }
50
51
        parent::setWriterByExtension($extension);
52
    }
53
54
    private function addLogoInMatchingFileFormat(): void
55
    {
56
        $this->setLogoPath(self::SWISS_CROSS_LOGO_FILE_PNG);
57
58
        if ($this->getWriter()->supportsExtension(self::FILE_FORMAT_SVG)) {
59
            $this->setLogoPath(self::SWISS_CROSS_LOGO_FILE_SVG);
60
            $this->setWriterOptions([
61
                'force_xlink_href' => true
62
            ]);
63
        }
64
    }
65
}
66