Common
11 months ago
Encoder
11 months ago
Exception
11 months ago
Renderer
11 months ago
Writer.php
11 months ago
Writer.php
57 lines
| 1 | <?php |
| 2 | |
| 3 | declare (strict_types=1); |
| 4 | namespace WP2FA_Vendor\BaconQrCode; |
| 5 | |
| 6 | use WP2FA_Vendor\BaconQrCode\Common\ErrorCorrectionLevel; |
| 7 | use WP2FA_Vendor\BaconQrCode\Common\Version; |
| 8 | use WP2FA_Vendor\BaconQrCode\Encoder\Encoder; |
| 9 | use WP2FA_Vendor\BaconQrCode\Exception\InvalidArgumentException; |
| 10 | use WP2FA_Vendor\BaconQrCode\Renderer\RendererInterface; |
| 11 | /** |
| 12 | * QR code writer. |
| 13 | */ |
| 14 | final class Writer |
| 15 | { |
| 16 | /** |
| 17 | * Renderer instance. |
| 18 | * |
| 19 | * @var RendererInterface |
| 20 | */ |
| 21 | private $renderer; |
| 22 | /** |
| 23 | * Creates a new writer with a specific renderer. |
| 24 | */ |
| 25 | public function __construct(RendererInterface $renderer) |
| 26 | { |
| 27 | $this->renderer = $renderer; |
| 28 | } |
| 29 | /** |
| 30 | * Writes QR code and returns it as string. |
| 31 | * |
| 32 | * Content is a string which *should* be encoded in UTF-8, in case there are |
| 33 | * non ASCII-characters present. |
| 34 | * |
| 35 | * @throws InvalidArgumentException if the content is empty |
| 36 | */ |
| 37 | public function writeString(string $content, string $encoding = Encoder::DEFAULT_BYTE_MODE_ECODING, ?ErrorCorrectionLevel $ecLevel = null, ?Version $forcedVersion = null) : string |
| 38 | { |
| 39 | if (\strlen($content) === 0) { |
| 40 | throw new InvalidArgumentException('Found empty contents'); |
| 41 | } |
| 42 | if (null === $ecLevel) { |
| 43 | $ecLevel = ErrorCorrectionLevel::L(); |
| 44 | } |
| 45 | return $this->renderer->render(Encoder::encode($content, $ecLevel, $encoding, $forcedVersion)); |
| 46 | } |
| 47 | /** |
| 48 | * Writes QR code to a file. |
| 49 | * |
| 50 | * @see Writer::writeString() |
| 51 | */ |
| 52 | public function writeFile(string $content, string $filename, string $encoding = Encoder::DEFAULT_BYTE_MODE_ECODING, ?ErrorCorrectionLevel $ecLevel = null, ?Version $forcedVersion = null) : void |
| 53 | { |
| 54 | \file_put_contents($filename, $this->writeString($content, $encoding, $ecLevel, $forcedVersion)); |
| 55 | } |
| 56 | } |
| 57 |