Debian Codegraph @

src/Encoder/ByteMatrix.php

raw
1 <?php
2 declare(strict_types = 1);
3
4 namespace BaconQrCode\Encoder;
5
6 use SplFixedArray;
7 use Traversable;
8
9 /**
10 * Byte matrix.
11 */
12 final class ByteMatrix
13 {
14 /**
15 * Bytes in the matrix, represented as array.
16 *
17 * @var SplFixedArray<SplFixedArray<int>>
18 */
19 private SplFixedArray $bytes;
20
21 public function __construct(private readonly int $width, private readonly int $height)
22 {
23 $this->bytes = new SplFixedArray($height);
24
25 for ($y = 0; $y < $height; ++$y) {
26 $this->bytes[$y] = SplFixedArray::fromArray(array_fill(0, $width, 0));
27 }
28 }
29
30 /**
31 * Gets the width of the matrix.
32 */
33 public function getWidth() : int
34 {
35 return $this->width;
36 }
37
38 /**
39 * Gets the height of the matrix.
40 */
41 public function getHeight() : int
42 {
43 return $this->height;
44 }
45
46 /**
47 * Gets the internal representation of the matrix.
48 *
49 * @return SplFixedArray<SplFixedArray<int>>
50 */
51 public function getArray() : SplFixedArray
52 {
53 return $this->bytes;
54 }
55
56 /**
57 * @return Traversable<int>
58 */
59 public function getBytes() : Traversable
60 {
61 foreach ($this->bytes as $row) {
62 foreach ($row as $byte) {
63 yield $byte;
64 }
65 }
66 }
67
68 /**
69 * Gets the byte for a specific position.
70 */
71 public function get(int $x, int $y) : int
72 {
73 return $this->bytes[$y][$x];
74 }
75
76 /**
77 * Sets the byte for a specific position.
78 */
79 public function set(int $x, int $y, int $value) : void
80 {
81 $this->bytes[$y][$x] = $value;
82 }
83
84 /**
85 * Clears the matrix with a specific value.
86 */
87 public function clear(int $value) : void
88 {
89 for ($y = 0; $y < $this->height; ++$y) {
90 for ($x = 0; $x < $this->width; ++$x) {
91 $this->bytes[$y][$x] = $value;
92 }
93 }
94 }
95
96 public function __clone()
97 {
98 $this->bytes = clone $this->bytes;
99
100 foreach ($this->bytes as $index => $row) {
101 $this->bytes[$index] = clone $row;
102 }
103 }
104
105 /**
106 * Returns a string representation of the matrix.
107 */
108 public function __toString() : string
109 {
110 $result = '';
111
112 for ($y = 0; $y < $this->height; $y++) {
113 for ($x = 0; $x < $this->width; $x++) {
114 switch ($this->bytes[$y][$x]) {
115 case 0:
116 $result .= ' 0';
117 break;
118
119 case 1:
120 $result .= ' 1';
121 break;
122
123 default:
124 $result .= ' ';
125 break;
126 }
127 }
128
129 $result .= "\n";
130 }
131
132 return $result;
133 }
134 }