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