Debian Codegraph @

vendor/chillerlan/php-qrcode/src/Data/QRMatrix.php

raw
1 <?php
2 /**
3 * Class QRMatrix
4 *
5 * @created 15.11.2017
6 * @author Smiley <[email protected]>
7 * @copyright 2017 Smiley
8 * @license MIT
9 */
10 declare(strict_types=1);
11
12 namespace chillerlan\QRCode\Data;
13
14 use chillerlan\QRCode\Common\{BitBuffer, EccLevel, MaskPattern, Version};
15 use chillerlan\QRCode\QRCodeException;
16 use function array_fill, array_map, array_reverse, count, intdiv, in_array;
17
18 /**
19 * Holds an array representation of the final QR Code that contains numerical values for later output modifications;
20 * maps the ECC coded binary data and applies the mask pattern
21 *
22 * @see http://www.thonky.com/qr-code-tutorial/format-version-information
23 *
24 * @property Version|null $version
25 * @property EccLevel|null $eccLevel
26 * @property MaskPattern|null $maskPattern
27 * @property int $moduleCount
28 * @property int[][] $matrix
29 */
30 class QRMatrix{
31
32 /*
33 * special values
34 */
35
36 /** @var int */
37 public const IS_DARK = 0b100000000000;
38 /** @var int */
39 public const M_NULL = 0b000000000000;
40 /** @var int */
41 public const M_LOGO = 0b001000000000;
42 /** @var int */
43 public const M_LOGO_DARK = 0b101000000000;
44
45 /*
46 * light values
47 */
48
49 /** @var int */
50 public const M_DATA = 0b000000000010;
51 /** @var int */
52 public const M_FINDER = 0b000000000100;
53 /** @var int */
54 public const M_SEPARATOR = 0b000000001000;
55 /** @var int */
56 public const M_ALIGNMENT = 0b000000010000;
57 /** @var int */
58 public const M_TIMING = 0b000000100000;
59 /** @var int */
60 public const M_FORMAT = 0b000001000000;
61 /** @var int */
62 public const M_VERSION = 0b000010000000;
63 /** @var int */
64 public const M_QUIETZONE = 0b000100000000;
65
66 /*
67 * dark values
68 */
69
70 /** @var int */
71 public const M_DARKMODULE = 0b100000000001;
72 /** @var int */
73 public const M_DATA_DARK = 0b100000000010;
74 /** @var int */
75 public const M_FINDER_DARK = 0b100000000100;
76 /** @var int */
77 public const M_ALIGNMENT_DARK = 0b100000010000;
78 /** @var int */
79 public const M_TIMING_DARK = 0b100000100000;
80 /** @var int */
81 public const M_FORMAT_DARK = 0b100001000000;
82 /** @var int */
83 public const M_VERSION_DARK = 0b100010000000;
84 /** @var int */
85 public const M_FINDER_DOT = 0b110000000000;
86
87 /*
88 * values used for reversed reflectance
89 */
90
91 /** @var int */
92 public const M_DARKMODULE_LIGHT = 0b000000000001;
93 /** @var int */
94 public const M_FINDER_DOT_LIGHT = 0b010000000000;
95 /** @var int */
96 public const M_SEPARATOR_DARK = 0b100000001000;
97 /** @var int */
98 public const M_QUIETZONE_DARK = 0b100100000000;
99
100 /**
101 * Map of flag => coord
102 *
103 * @see \chillerlan\QRCode\Data\QRMatrix::checkNeighbours()
104 *
105 * @var int[][]
106 */
107 protected const neighbours = [
108 0b00000001 => [-1, -1],
109 0b00000010 => [ 0, -1],
110 0b00000100 => [ 1, -1],
111 0b00001000 => [ 1, 0],
112 0b00010000 => [ 1, 1],
113 0b00100000 => [ 0, 1],
114 0b01000000 => [-1, 1],
115 0b10000000 => [-1, 0],
116 ];
117
118 /**
119 * the matrix version - always set in QRMatrix, may be null in BitMatrix
120 */
121 protected Version|null $version = null;
122
123 /**
124 * the current ECC level - always set in QRMatrix, may be null in BitMatrix
125 */
126 protected EccLevel|null $eccLevel = null;
127
128 /**
129 * the mask pattern that was used in the most recent operation, set via:
130 *
131 * - QRMatrix::setFormatInfo()
132 * - QRMatrix::mask()
133 * - BitMatrix::readFormatInformation()
134 */
135 protected MaskPattern|null $maskPattern = null;
136
137 /**
138 * the size (side length) of the matrix, including quiet zone (if created)
139 */
140 protected int $moduleCount;
141
142 /**
143 * the actual matrix data array
144 *
145 * @var int[][]
146 */
147 protected array $matrix;
148
149 /**
150 * QRMatrix constructor.
151 */
152 public function __construct(Version $version, EccLevel $eccLevel){
153 $this->version = $version;
154 $this->eccLevel = $eccLevel;
155 $this->moduleCount = $this->version->getDimension();
156 $this->matrix = $this->createMatrix($this->moduleCount, $this::M_NULL);
157 }
158
159 /**
160 * This magic getter serves as an upgrade path for the deprecated property getter methods,
161 * which will be removed in v7 in favor of asymmetric visibility (PHP 8.4+).
162 *
163 * @throws \chillerlan\QRCode\QRCodeException
164 * @codeCoverageIgnore
165 */
166 public function __get(string $name):mixed{
167
168 if(in_array($name, ['matrix', 'version', 'eccLevel', 'maskPattern', 'moduleCount'], true)){
169 return $this->{$name};
170 }
171
172 throw new QRCodeException('invalid property access');
173 }
174
175 /**
176 * Creates a 2-dimensional array (square) of the given $size
177 *
178 * @return int[][]
179 */
180 protected function createMatrix(int $size, int $value):array{
181 return array_fill(0, $size, array_fill(0, $size, $value));
182 }
183
184 /**
185 * shortcut to initialize the functional patterns
186 */
187 public function initFunctionalPatterns():static{
188 return $this
189 ->setFinderPattern()
190 ->setSeparators()
191 ->setAlignmentPattern()
192 ->setTimingPattern()
193 ->setDarkModule()
194 ->setVersionNumber()
195 ->setFormatInfo()
196 ;
197 }
198
199 /**
200 * Returns the data matrix
201 *
202 * @return int[][]
203 *
204 * @deprecated 6.0.1 This method will be removed in v7, use the property "QRMatrix::$matrix" instead.
205 */
206 public function getMatrix():array{
207 return $this->matrix;
208 }
209
210 /**
211 * Returns a boolean representation of the data matrix
212 *
213 * @return bool[][]
214 * @phan-suppress PhanTypeMismatchReturn
215 */
216 public function getBooleanMatrix():array{
217 $matrix = $this->matrix;
218
219 foreach($matrix as &$row){
220 $row = array_map($this->isDark(...), $row);
221 }
222 /** @var bool[][] $matrix (phpstan hates this otherwise) */
223 return $matrix;
224 }
225
226 /**
227 * Returns the current version number
228 *
229 * @deprecated 6.0.1 This method will be removed in v7, use the property "QRMatrix::$version" instead.
230 */
231 public function getVersion():Version|null{
232 return $this->version;
233 }
234
235 /**
236 * Returns the current ECC level
237 *
238 * @deprecated 6.0.1 This method will be removed in v7, use the property "QRMatrix::$eccLevel" instead.
239 */
240 public function getEccLevel():EccLevel|null{
241 return $this->eccLevel;
242 }
243
244 /**
245 * Returns the current mask pattern
246 *
247 * @deprecated 6.0.1 This method will be removed in v7, use the property "QRMatrix::$maskPattern" instead.
248 */
249 public function getMaskPattern():MaskPattern|null{
250 return $this->maskPattern;
251 }
252
253 /**
254 * Returns the absoulute size of the matrix, including quiet zone (after setting it).
255 *
256 * size = version * 4 + 17 [ + 2 * quietzone size]
257 *
258 * @deprecated 6.0.1 This method will be removed in v7, use the property "QRMatrix::$moduleCount" instead.
259 */
260 public function getSize():int{
261 return $this->moduleCount;
262 }
263
264 /**
265 * Returns the value of the module at position [$x, $y] or -1 if the coordinate is outside the matrix
266 */
267 public function get(int $x, int $y):int{
268
269 if(!isset($this->matrix[$y][$x])){
270 return -1;
271 }
272
273 return $this->matrix[$y][$x];
274 }
275
276 /**
277 * Sets the $M_TYPE value for the module at position [$x, $y]
278 *
279 * true => $M_TYPE | 0x800
280 * false => $M_TYPE
281 */
282 public function set(int $x, int $y, bool $value, int $M_TYPE):static{
283
284 if(isset($this->matrix[$y][$x])){
285 // we don't know whether the input is dark, so we remove the dark bit
286 $M_TYPE &= ~$this::IS_DARK;
287
288 if($value === true){
289 $M_TYPE |= $this::IS_DARK;
290 }
291
292 $this->matrix[$y][$x] = $M_TYPE;
293 }
294
295 return $this;
296 }
297
298 /**
299 * Fills an area of $width * $height, from the given starting point [$startX, $startY] (top left) with $value for $M_TYPE.
300 */
301 public function setArea(int $startX, int $startY, int $width, int $height, bool $value, int $M_TYPE):static{
302
303 for($y = $startY; $y < ($startY + $height); $y++){
304 for($x = $startX; $x < ($startX + $width); $x++){
305 $this->set($x, $y, $value, $M_TYPE);
306 }
307 }
308
309 return $this;
310 }
311
312 /**
313 * Flips the value of the module at ($x, $y)
314 */
315 public function flip(int $x, int $y):static{
316
317 if(isset($this->matrix[$y][$x])){
318 $this->matrix[$y][$x] ^= $this::IS_DARK;
319 }
320
321 return $this;
322 }
323
324 /**
325 * Checks whether the module at ($x, $y) is of the given $M_TYPE
326 *
327 * true => $value & $M_TYPE === $M_TYPE
328 *
329 * Also, returns false if the given coordinates are out of range.
330 */
331 public function checkType(int $x, int $y, int $M_TYPE):bool{
332
333 if(isset($this->matrix[$y][$x])){
334 return ($this->matrix[$y][$x] & $M_TYPE) === $M_TYPE;
335 }
336
337 return false;
338 }
339
340 /**
341 * Checks whether the module at ($x, $y) is in the given array of $M_TYPES,
342 * returns true if a match is found, otherwise false.
343 *
344 * @param int[] $M_TYPES
345 */
346 public function checkTypeIn(int $x, int $y, array $M_TYPES):bool{
347
348 foreach($M_TYPES as $type){
349 if($this->checkType($x, $y, $type)){
350 return true;
351 }
352 }
353
354 return false;
355 }
356
357 /**
358 * Checks whether the module at ($x, $y) is true (dark) or false (light)
359 *
360 * Also, returns false if the given coordinates are out of range.
361 */
362 public function check(int $x, int $y):bool{
363
364 if(isset($this->matrix[$y][$x])){
365 return $this->isDark($this->matrix[$y][$x]);
366 }
367
368 return false;
369 }
370
371 /**
372 * Checks whether the given $M_TYPE is a dark value
373 */
374 public function isDark(int $M_TYPE):bool{
375 return ($M_TYPE & $this::IS_DARK) === $this::IS_DARK;
376 }
377
378 /**
379 * Checks the status of the neighbouring modules for the module at ($x, $y) and returns a bitmask with the results.
380 *
381 * The 8 flags of the bitmask represent the status of each of the neighbouring fields,
382 * starting with the lowest bit for top left, going clockwise:
383 *
384 * 0 1 2
385 * 7 # 3
386 * 6 5 4
387 */
388 public function checkNeighbours(int $x, int $y, int|null $M_TYPE = null):int{
389 $bits = 0;
390
391 foreach($this::neighbours as $bit => [$ix, $iy]){
392 $ix += $x;
393 $iy += $y;
394
395 // check if the field is the same type
396 if($M_TYPE !== null && !$this->checkType($ix, $iy, $M_TYPE)){
397 continue;
398 }
399
400 if($this->checkType($ix, $iy, $this::IS_DARK)){
401 $bits |= $bit;
402 }
403 }
404
405 return $bits;
406 }
407
408 /**
409 * Sets the "dark module", that is always on the same position 1x1px away from the bottom left finder
410 *
411 * 4 * version + 9 or moduleCount - 8
412 */
413 public function setDarkModule():static{
414 $this->set(8, ($this->moduleCount - 8), true, $this::M_DARKMODULE);
415
416 return $this;
417 }
418
419 /**
420 * Draws the 7x7 finder patterns in the corners top left/right and bottom left
421 *
422 * ISO/IEC 18004:2000 Section 7.3.2
423 */
424 public function setFinderPattern():static{
425
426 $pos = [
427 [0, 0], // top left
428 [($this->moduleCount - 7), 0], // top right
429 [0, ($this->moduleCount - 7)], // bottom left
430 ];
431
432 foreach($pos as $c){
433 $this
434 // phpcs:ignore
435 ->setArea( $c[0] , $c[1] , 7, 7, true, $this::M_FINDER)
436 ->setArea(($c[0] + 1), ($c[1] + 1), 5, 5, false, $this::M_FINDER)
437 ->setArea(($c[0] + 2), ($c[1] + 2), 3, 3, true, $this::M_FINDER_DOT)
438 ;
439 }
440
441 return $this;
442 }
443
444 /**
445 * Draws the separator lines around the finder patterns
446 *
447 * ISO/IEC 18004:2000 Section 7.3.3
448 */
449 public function setSeparators():static{
450
451 $h = [
452 [7, 0],
453 [($this->moduleCount - 8), 0],
454 [7, ($this->moduleCount - 8)],
455 ];
456
457 $v = [
458 [7, 7],
459 [($this->moduleCount - 1), 7],
460 [7, ($this->moduleCount - 8)],
461 ];
462
463 for($c = 0; $c < 3; $c++){
464 for($i = 0; $i < 8; $i++){
465 // phpcs:ignore
466 $this->set( $h[$c][0] , ($h[$c][1] + $i), false, $this::M_SEPARATOR);
467 $this->set(($v[$c][0] - $i), $v[$c][1] , false, $this::M_SEPARATOR);
468 }
469 }
470
471 return $this;
472 }
473
474
475 /**
476 * Draws the 5x5 alignment patterns
477 *
478 * ISO/IEC 18004:2000 Section 7.3.5
479 */
480 public function setAlignmentPattern():static{
481 $alignmentPattern = $this->version->getAlignmentPattern();
482
483 foreach($alignmentPattern as $y){
484 foreach($alignmentPattern as $x){
485
486 // skip existing patterns
487 if($this->matrix[$y][$x] !== $this::M_NULL){
488 continue;
489 }
490
491 $this
492 ->setArea(($x - 2), ($y - 2), 5, 5, true, $this::M_ALIGNMENT)
493 ->setArea(($x - 1), ($y - 1), 3, 3, false, $this::M_ALIGNMENT)
494 ->set($x, $y, true, $this::M_ALIGNMENT)
495 ;
496
497 }
498 }
499
500 return $this;
501 }
502
503
504 /**
505 * Draws the timing pattern (h/v checkered line between the finder patterns)
506 *
507 * ISO/IEC 18004:2000 Section 7.3.4
508 */
509 public function setTimingPattern():static{
510
511 for($i = 8; $i < ($this->moduleCount - 8); $i++){
512
513 if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
514 continue;
515 }
516
517 $v = ($i % 2) === 0;
518
519 $this->set($i, 6, $v, $this::M_TIMING); // h
520 $this->set(6, $i, $v, $this::M_TIMING); // v
521 }
522
523 return $this;
524 }
525
526 /**
527 * Draws the version information, 2x 3x6 pixel
528 *
529 * ISO/IEC 18004:2000 Section 8.10
530 */
531 public function setVersionNumber():static{
532 $bits = $this->version->getVersionPattern();
533
534 if($bits !== null){
535
536 for($i = 0; $i < 18; $i++){
537 $a = intdiv($i, 3);
538 $b = (($i % 3) + ($this->moduleCount - 8 - 3));
539 $v = (($bits >> $i) & 1) === 1;
540
541 $this->set($b, $a, $v, $this::M_VERSION); // ne
542 $this->set($a, $b, $v, $this::M_VERSION); // sw
543 }
544
545 }
546
547 return $this;
548 }
549
550 /**
551 * Draws the format info along the finder patterns. If no $maskPattern, all format info modules will be set to false.
552 *
553 * ISO/IEC 18004:2000 Section 8.9
554 */
555 public function setFormatInfo(MaskPattern|null $maskPattern = null):static{
556 $this->maskPattern = $maskPattern;
557 $bits = 0; // sets all format fields to false (test mode)
558
559 if($this->maskPattern instanceof MaskPattern){
560 $bits = $this->eccLevel->getformatPattern($this->maskPattern);
561 }
562
563 for($i = 0; $i < 15; $i++){
564 $v = (($bits >> $i) & 1) === 1;
565
566 if($i < 6){
567 $this->set(8, $i, $v, $this::M_FORMAT);
568 }
569 elseif($i < 8){
570 $this->set(8, ($i + 1), $v, $this::M_FORMAT);
571 }
572 else{
573 $this->set(8, ($this->moduleCount - 15 + $i), $v, $this::M_FORMAT);
574 }
575
576 if($i < 8){
577 $this->set(($this->moduleCount - $i - 1), 8, $v, $this::M_FORMAT);
578 }
579 elseif($i < 9){
580 $this->set(((15 - $i)), 8, $v, $this::M_FORMAT);
581 }
582 else{
583 $this->set((15 - $i - 1), 8, $v, $this::M_FORMAT);
584 }
585
586 }
587
588 return $this;
589 }
590
591 /**
592 * Draws the "quiet zone" of $size around the matrix
593 *
594 * ISO/IEC 18004:2000 Section 7.3.7
595 *
596 * @throws \chillerlan\QRCode\Data\QRCodeDataException
597 */
598 public function setQuietZone(int $quietZoneSize):static{
599
600 // early exit if there's nothing to add
601 if($quietZoneSize < 1){
602 return $this;
603 }
604
605 if($this->matrix[($this->moduleCount - 1)][($this->moduleCount - 1)] === $this::M_NULL){
606 throw new QRCodeDataException('use only after writing data');
607 }
608
609 // create a matrix with the new size
610 $newSize = ($this->moduleCount + ($quietZoneSize * 2));
611 $newMatrix = $this->createMatrix($newSize, $this::M_QUIETZONE);
612
613 // copy over the current matrix
614 foreach($this->matrix as $y => $row){
615 foreach($row as $x => $val){
616 $newMatrix[($y + $quietZoneSize)][($x + $quietZoneSize)] = $val;
617 }
618 }
619
620 // set the new values
621 $this->moduleCount = $newSize;
622 $this->matrix = $newMatrix;
623
624 return $this;
625 }
626
627 /**
628 * Rotates the matrix by 90 degrees clock wise
629 */
630 public function rotate90():static{
631 /** @phan-suppress-next-line PhanParamTooFewInternalUnpack */
632 $this->matrix = array_map((fn(int ...$a):array => array_reverse($a)), ...$this->matrix);
633
634 return $this;
635 }
636
637 /**
638 * Inverts the values of the whole matrix
639 *
640 * ISO/IEC 18004:2015 Section 6.2 - Reflectance reversal
641 */
642 public function invert():static{
643
644 foreach($this->matrix as $y => $row){
645 foreach($row as $x => $val){
646
647 // skip null fields
648 if($val === $this::M_NULL){
649 continue;
650 }
651
652 $this->flip($x, $y);
653 }
654 }
655
656 return $this;
657 }
658
659 /**
660 * Clears a space of $width * $height in order to add a logo or text.
661 * If no $height is given, the space will be assumed a square of $width.
662 *
663 * Additionally, the logo space can be positioned within the QR Code using $startX and $startY.
664 * If either of these are null, the logo space will be centered in that direction.
665 * ECC level "H" (30%) is required.
666 *
667 * The coordinates of $startX and $startY do not include the quiet zone:
668 * [0, 0] is always the top left module of the top left finder pattern, negative values go into the quiet zone top and left.
669 *
670 * Please note that adding a logo space minimizes the error correction capacity of the QR Code and
671 * created images may become unreadable, especially when printed with a chance to receive damage.
672 * Please test thoroughly before using this feature in production.
673 *
674 * This method should be called from within an output module (after the matrix has been filled with data).
675 * Note that there is no restiction on how many times this method could be called on the same matrix instance.
676 *
677 * @link https://github.com/chillerlan/php-qrcode/issues/52
678 *
679 * @throws \chillerlan\QRCode\Data\QRCodeDataException
680 */
681 public function setLogoSpace(int $width, int|null $height = null, int|null $startX = null, int|null $startY = null):static{
682 $height ??= $width;
683
684 // if width and height happen to be negative or 0 (default value), just return - nothing to do
685 if($width <= 0 || $height <= 0){
686 return $this; // @codeCoverageIgnore
687 }
688
689 // for logos, we operate in ECC H (30%) only
690 if($this->eccLevel->getLevel() !== EccLevel::H){
691 throw new QRCodeDataException('ECC level "H" required to add logo space');
692 }
693
694 // $this->moduleCount includes the quiet zone (if created), we need the QR size here
695 $dimension = $this->version->getDimension();
696
697 // throw if the size exceeds the qrcode size
698 if($width > $dimension || $height > $dimension){
699 throw new QRCodeDataException('logo dimensions exceed matrix size');
700 }
701
702 // we need uneven sizes to center the logo space, adjust if needed
703 if($startX === null && ($width % 2) === 0){
704 $width++;
705 }
706
707 if($startY === null && ($height % 2) === 0){
708 $height++;
709 }
710
711 // throw if the logo space exceeds the maximum error correction capacity
712 if(($width * $height) > (int)($dimension * $dimension * 0.25)){
713 throw new QRCodeDataException('logo space exceeds the maximum error correction capacity');
714 }
715
716 $quietzone = (($this->moduleCount - $dimension) / 2);
717 $end = ($this->moduleCount - $quietzone);
718
719 // determine start coordinates
720 $startX ??= (($dimension - $width) / 2);
721 $startY ??= (($dimension - $height) / 2);
722 $endX = ($quietzone + $startX + $width);
723 $endY = ($quietzone + $startY + $height);
724
725 // clear the space
726 for($y = ($quietzone + $startY); $y < $endY; $y++){
727 for($x = ($quietzone + $startX); $x < $endX; $x++){
728 // out of bounds, skip
729 if($x < $quietzone || $y < $quietzone ||$x >= $end || $y >= $end){
730 continue;
731 }
732
733 $this->set($x, $y, false, $this::M_LOGO);
734 }
735 }
736
737 return $this;
738 }
739
740 /**
741 * Maps the interleaved binary $data on the matrix
742 */
743 public function writeCodewords(BitBuffer $bitBuffer):static{
744 $data = (new ReedSolomonEncoder($this->version, $this->eccLevel))->interleaveEcBytes($bitBuffer);
745 $byteCount = count($data);
746 $iByte = 0;
747 $iBit = 7;
748 $direction = true;
749
750 for($i = ($this->moduleCount - 1); $i > 0; $i -= 2){
751
752 // skip vertical alignment pattern
753 if($i === 6){
754 $i--;
755 }
756
757 for($count = 0; $count < $this->moduleCount; $count++){
758 $y = $count;
759
760 if($direction){
761 $y = ($this->moduleCount - 1 - $count);
762 }
763
764 for($col = 0; $col < 2; $col++){
765 $x = ($i - $col);
766
767 // skip functional patterns
768 if($this->matrix[$y][$x] !== $this::M_NULL){
769 continue;
770 }
771
772 $this->matrix[$y][$x] = $this::M_DATA;
773
774 if($iByte < $byteCount && (($data[$iByte] >> $iBit--) & 1) === 1){
775 $this->matrix[$y][$x] |= $this::IS_DARK;
776 }
777
778 if($iBit === -1){
779 $iByte++;
780 $iBit = 7;
781 }
782 }
783 }
784
785 $direction = !$direction; // switch directions
786 }
787
788 return $this;
789 }
790
791 /**
792 * Applies/reverses the mask pattern
793 *
794 * ISO/IEC 18004:2000 Section 8.8.1
795 */
796 public function mask(MaskPattern $maskPattern):static{
797 $this->maskPattern = $maskPattern;
798 $mask = $this->maskPattern->getMask();
799
800 foreach($this->matrix as $y => $row){
801 foreach($row as $x => $val){
802 // skip non-data modules
803 if(($val & $this::M_DATA) === $this::M_DATA && $mask($x, $y)){
804 $this->flip($x, $y);
805 }
806 }
807 }
808
809 return $this;
810 }
811
812 }