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