PlainTextRenderer.php 2.1 KB

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