Passed
Pull Request — master (#40)
by Manuel
02:28
created

QrCode::setWriterByExtension()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 11
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Sprain\SwissQrBill\QrCode;
4
5
use Endroid\QrCode\Exception\UnsupportedExtensionException;
6
use Endroid\QrCode\QrCode as BaseQrCode;
7
use Endroid\QrCode\QrCodeInterface;
8
use Sprain\SwissQrBill\QrCode\Exception\UnsupportedFileExtensionException;
9
10
class QrCode extends BaseQrCode implements QrCodeInterface
11
{
12
    const FILE_FORMAT_PNG = 'png';
13
    const FILE_FORMAT_SVG = 'svg';
14
15
    // A file extension is supported if the underlying library supports it,
16
    // including the possibility to add a logo in the center of the qr code.
17
    const SUPPORTED_FILE_FORMATS = [
18
        self::FILE_FORMAT_PNG,
19
        self::FILE_FORMAT_SVG
20
    ];
21
22
    public function writeFile(string $path): void
23
    {
24
        $extension = strtolower(pathinfo($path, PATHINFO_EXTENSION));
25
        $this->setWriterByExtension($extension);
26
        parent::writeFile($path);
27
    }
28
29
    public function setWriterByExtension(string $extension): void
30
    {
31
        if (!in_array($extension, self::SUPPORTED_FILE_FORMATS)) {
32
            throw new UnsupportedFileExtensionException(sprintf(
33
                'Your file cannot be created. Only these file extensions are supported: %s. You provided: %s.',
34
                implode(', ', self::SUPPORTED_FILE_FORMATS),
35
                $extension
36
            ));
37
        }
38
39
        parent::setWriterByExtension($extension);
40
    }
41
42
}