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