| 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 |
public function __construct(private readonly int $margin = 2) |
| 32 |
{ |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* @throws InvalidArgumentException if matrix width doesn't match height |
| 37 |
*/ |
| 38 |
public function render(QrCode $qrCode) : string |
| 39 |
{ |
| 40 |
$matrix = $qrCode->getMatrix(); |
| 41 |
$matrixSize = $matrix->getWidth(); |
| 42 |
|
| 43 |
if ($matrixSize !== $matrix->getHeight()) { |
| 44 |
throw new InvalidArgumentException('Matrix must have the same width and height'); |
| 45 |
} |
| 46 |
|
| 47 |
$rows = $matrix->getArray()->toArray(); |
| 48 |
|
| 49 |
if (0 !== $matrixSize % 2) { |
| 50 |
$rows[] = array_fill(0, $matrixSize, 0); |
| 51 |
} |
| 52 |
|
| 53 |
$horizontalMargin = str_repeat(self::EMPTY_BLOCK, $this->margin); |
| 54 |
$result = str_repeat("\n", (int) ceil($this->margin / 2)); |
| 55 |
|
| 56 |
for ($i = 0; $i < $matrixSize; $i += 2) { |
| 57 |
$result .= $horizontalMargin; |
| 58 |
|
| 59 |
$upperRow = $rows[$i]; |
| 60 |
$lowerRow = $rows[$i + 1]; |
| 61 |
|
| 62 |
for ($j = 0; $j < $matrixSize; ++$j) { |
| 63 |
$upperBit = $upperRow[$j]; |
| 64 |
$lowerBit = $lowerRow[$j]; |
| 65 |
|
| 66 |
if ($upperBit) { |
| 67 |
$result .= $lowerBit ? self::FULL_BLOCK : self::UPPER_HALF_BLOCK; |
| 68 |
} else { |
| 69 |
$result .= $lowerBit ? self::LOWER_HALF_BLOCK : self::EMPTY_BLOCK; |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
$result .= $horizontalMargin . "\n"; |
| 74 |
} |
| 75 |
|
| 76 |
$result .= str_repeat("\n", (int) ceil($this->margin / 2)); |
| 77 |
|
| 78 |
return $result; |
| 79 |
} |
| 80 |
} |