Edge.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. declare(strict_types = 1);
  3. namespace BaconQrCode\Renderer\Module\EdgeIterator;
  4. final class Edge
  5. {
  6. /**
  7. * @var bool
  8. */
  9. private $positive;
  10. /**
  11. * @var array<int[]>
  12. */
  13. private $points = [];
  14. /**
  15. * @var array<int[]>|null
  16. */
  17. private $simplifiedPoints;
  18. /**
  19. * @var int
  20. */
  21. private $minX = PHP_INT_MAX;
  22. /**
  23. * @var int
  24. */
  25. private $minY = PHP_INT_MAX;
  26. /**
  27. * @var int
  28. */
  29. private $maxX = -1;
  30. /**
  31. * @var int
  32. */
  33. private $maxY = -1;
  34. public function __construct(bool $positive)
  35. {
  36. $this->positive = $positive;
  37. }
  38. public function addPoint(int $x, int $y) : void
  39. {
  40. $this->points[] = [$x, $y];
  41. $this->minX = min($this->minX, $x);
  42. $this->minY = min($this->minY, $y);
  43. $this->maxX = max($this->maxX, $x);
  44. $this->maxY = max($this->maxY, $y);
  45. }
  46. public function isPositive() : bool
  47. {
  48. return $this->positive;
  49. }
  50. /**
  51. * @return array<int[]>
  52. */
  53. public function getPoints() : array
  54. {
  55. return $this->points;
  56. }
  57. public function getMaxX() : int
  58. {
  59. return $this->maxX;
  60. }
  61. public function getSimplifiedPoints() : array
  62. {
  63. if (null !== $this->simplifiedPoints) {
  64. return $this->simplifiedPoints;
  65. }
  66. $points = [];
  67. $length = count($this->points);
  68. for ($i = 0; $i < $length; ++$i) {
  69. $previousPoint = $this->points[(0 === $i ? $length : $i) - 1];
  70. $nextPoint = $this->points[($length - 1 === $i ? -1 : $i) + 1];
  71. $currentPoint = $this->points[$i];
  72. if (($previousPoint[0] === $currentPoint[0] && $currentPoint[0] === $nextPoint[0])
  73. || ($previousPoint[1] === $currentPoint[1] && $currentPoint[1] === $nextPoint[1])
  74. ) {
  75. continue;
  76. }
  77. $points[] = $currentPoint;
  78. }
  79. return $this->simplifiedPoints = $points;
  80. }
  81. }