Color
8 months ago
Eye
8 months ago
Image
8 months ago
Module
8 months ago
Path
8 months ago
RendererStyle
8 months ago
ImageRenderer.php
8 months ago
PlainTextRenderer.php
8 months ago
RendererInterface.php
8 months ago
PlainTextRenderer.php
87 lines
| 1 | <?php |
| 2 | declare(strict_types = 1); |
| 3 | |
| 4 | namespace BaconQrCode\Renderer; |
| 5 | |
| 6 | use BaconQrCode\Encoder\QrCode; |
| 7 | use BaconQrCode\Exception\InvalidArgumentException; |
| 8 | |
| 9 | final class PlainTextRenderer implements RendererInterface |
| 10 | { |
| 11 | /** |
| 12 | * UTF-8 full block (U+2588) |
| 13 | */ |
| 14 | private const FULL_BLOCK = "\xe2\x96\x88"; |
| 15 | |
| 16 | /** |
| 17 | * UTF-8 upper half block (U+2580) |
| 18 | */ |
| 19 | private const UPPER_HALF_BLOCK = "\xe2\x96\x80"; |
| 20 | |
| 21 | /** |
| 22 | * UTF-8 lower half block (U+2584) |
| 23 | */ |
| 24 | private const LOWER_HALF_BLOCK = "\xe2\x96\x84"; |
| 25 | |
| 26 | /** |
| 27 | * UTF-8 no-break space (U+00A0) |
| 28 | */ |
| 29 | private const EMPTY_BLOCK = "\xc2\xa0"; |
| 30 | |
| 31 | /** |
| 32 | * @var int |
| 33 | */ |
| 34 | private $margin; |
| 35 | |
| 36 | public function __construct(int $margin = 2) |
| 37 | { |
| 38 | $this->margin = $margin; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * @throws InvalidArgumentException if matrix width doesn't match height |
| 43 | */ |
| 44 | public function render(QrCode $qrCode) : string |
| 45 | { |
| 46 | $matrix = $qrCode->getMatrix(); |
| 47 | $matrixSize = $matrix->getWidth(); |
| 48 | |
| 49 | if ($matrixSize !== $matrix->getHeight()) { |
| 50 | throw new InvalidArgumentException('Matrix must have the same width and height'); |
| 51 | } |
| 52 | |
| 53 | $rows = $matrix->getArray()->toArray(); |
| 54 | |
| 55 | if (0 !== $matrixSize % 2) { |
| 56 | $rows[] = array_fill(0, $matrixSize, 0); |
| 57 | } |
| 58 | |
| 59 | $horizontalMargin = str_repeat(self::EMPTY_BLOCK, $this->margin); |
| 60 | $result = str_repeat("\n", (int) ceil($this->margin / 2)); |
| 61 | |
| 62 | for ($i = 0; $i < $matrixSize; $i += 2) { |
| 63 | $result .= $horizontalMargin; |
| 64 | |
| 65 | $upperRow = $rows[$i]; |
| 66 | $lowerRow = $rows[$i + 1]; |
| 67 | |
| 68 | for ($j = 0; $j < $matrixSize; ++$j) { |
| 69 | $upperBit = $upperRow[$j]; |
| 70 | $lowerBit = $lowerRow[$j]; |
| 71 | |
| 72 | if ($upperBit) { |
| 73 | $result .= $lowerBit ? self::FULL_BLOCK : self::UPPER_HALF_BLOCK; |
| 74 | } else { |
| 75 | $result .= $lowerBit ? self::LOWER_HALF_BLOCK : self::EMPTY_BLOCK; |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | $result .= $horizontalMargin . "\n"; |
| 80 | } |
| 81 | |
| 82 | $result .= str_repeat("\n", (int) ceil($this->margin / 2)); |
| 83 | |
| 84 | return $result; |
| 85 | } |
| 86 | } |
| 87 |