Passed
Push — master ( 552d15...d4c1db )
by smiley
02:51
created

QRMatrix::setSeparators()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 22
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 11
nc 3
nop 0
dl 0
loc 22
rs 9.9
c 2
b 0
f 0
1
<?php
2
/**
3
 * Class QRMatrix
4
 *
5
 * @filesource   QRMatrix.php
6
 * @created      15.11.2017
7
 * @package      chillerlan\QRCode\Data
8
 * @author       Smiley <[email protected]>
9
 * @copyright    2017 Smiley
10
 * @license      MIT
11
 */
12
13
namespace chillerlan\QRCode\Data;
14
15
use chillerlan\QRCode\QRCode;
16
use Closure;
17
18
use function array_fill, array_key_exists, array_push, array_unshift, count, floor, in_array, max, min, range;
19
20
/**
21
 * Holds a numerical representation of the final QR Code;
22
 * maps the ECC coded binary data and applies the mask pattern
23
 *
24
 * @see http://www.thonky.com/qr-code-tutorial/format-version-information
25
 */
26
final class QRMatrix{
27
28
	/** @var int */
29
	public const M_NULL       = 0x00;
30
	/** @var int */
31
	public const M_DARKMODULE = 0x02;
32
	/** @var int */
33
	public const M_DATA       = 0x04;
34
	/** @var int */
35
	public const M_FINDER     = 0x06;
36
	/** @var int */
37
	public const M_SEPARATOR  = 0x08;
38
	/** @var int */
39
	public const M_ALIGNMENT  = 0x0a;
40
	/** @var int */
41
	public const M_TIMING     = 0x0c;
42
	/** @var int */
43
	public const M_FORMAT     = 0x0e;
44
	/** @var int */
45
	public const M_VERSION    = 0x10;
46
	/** @var int */
47
	public const M_QUIETZONE  = 0x12;
48
49
#	public const M_LOGO       = 0x14; // @todo
50
	/** @var int */
51
	public const M_TEST       = 0xff;
52
53
	/**
54
	 * ISO/IEC 18004:2000 Annex E, Table E.1 - Row/column coordinates of center module of Alignment Patterns
55
	 *
56
	 * version -> pattern
57
	 *
58
	 * @var int[][]
59
	 */
60
	protected const alignmentPattern = [
61
		1  => [],
62
		2  => [6, 18],
63
		3  => [6, 22],
64
		4  => [6, 26],
65
		5  => [6, 30],
66
		6  => [6, 34],
67
		7  => [6, 22, 38],
68
		8  => [6, 24, 42],
69
		9  => [6, 26, 46],
70
		10 => [6, 28, 50],
71
		11 => [6, 30, 54],
72
		12 => [6, 32, 58],
73
		13 => [6, 34, 62],
74
		14 => [6, 26, 46, 66],
75
		15 => [6, 26, 48, 70],
76
		16 => [6, 26, 50, 74],
77
		17 => [6, 30, 54, 78],
78
		18 => [6, 30, 56, 82],
79
		19 => [6, 30, 58, 86],
80
		20 => [6, 34, 62, 90],
81
		21 => [6, 28, 50, 72,  94],
82
		22 => [6, 26, 50, 74,  98],
83
		23 => [6, 30, 54, 78, 102],
84
		24 => [6, 28, 54, 80, 106],
85
		25 => [6, 32, 58, 84, 110],
86
		26 => [6, 30, 58, 86, 114],
87
		27 => [6, 34, 62, 90, 118],
88
		28 => [6, 26, 50, 74,  98, 122],
89
		29 => [6, 30, 54, 78, 102, 126],
90
		30 => [6, 26, 52, 78, 104, 130],
91
		31 => [6, 30, 56, 82, 108, 134],
92
		32 => [6, 34, 60, 86, 112, 138],
93
		33 => [6, 30, 58, 86, 114, 142],
94
		34 => [6, 34, 62, 90, 118, 146],
95
		35 => [6, 30, 54, 78, 102, 126, 150],
96
		36 => [6, 24, 50, 76, 102, 128, 154],
97
		37 => [6, 28, 54, 80, 106, 132, 158],
98
		38 => [6, 32, 58, 84, 110, 136, 162],
99
		39 => [6, 26, 54, 82, 110, 138, 166],
100
		40 => [6, 30, 58, 86, 114, 142, 170],
101
	];
102
103
	/**
104
	 * ISO/IEC 18004:2000 Annex D, Table D.1 - Version information bit stream for each version
105
	 *
106
	 * no version pattern for QR Codes < 7
107
	 *
108
	 * @var int[]
109
	 */
110
	protected const versionPattern = [
111
		7  => 0b000111110010010100,
112
		8  => 0b001000010110111100,
113
		9  => 0b001001101010011001,
114
		10 => 0b001010010011010011,
115
		11 => 0b001011101111110110,
116
		12 => 0b001100011101100010,
117
		13 => 0b001101100001000111,
118
		14 => 0b001110011000001101,
119
		15 => 0b001111100100101000,
120
		16 => 0b010000101101111000,
121
		17 => 0b010001010001011101,
122
		18 => 0b010010101000010111,
123
		19 => 0b010011010100110010,
124
		20 => 0b010100100110100110,
125
		21 => 0b010101011010000011,
126
		22 => 0b010110100011001001,
127
		23 => 0b010111011111101100,
128
		24 => 0b011000111011000100,
129
		25 => 0b011001000111100001,
130
		26 => 0b011010111110101011,
131
		27 => 0b011011000010001110,
132
		28 => 0b011100110000011010,
133
		29 => 0b011101001100111111,
134
		30 => 0b011110110101110101,
135
		31 => 0b011111001001010000,
136
		32 => 0b100000100111010101,
137
		33 => 0b100001011011110000,
138
		34 => 0b100010100010111010,
139
		35 => 0b100011011110011111,
140
		36 => 0b100100101100001011,
141
		37 => 0b100101010000101110,
142
		38 => 0b100110101001100100,
143
		39 => 0b100111010101000001,
144
		40 => 0b101000110001101001,
145
	];
146
147
	/**
148
	 * ISO/IEC 18004:2000 Section 8.9 - Format Information
149
	 *
150
	 * ECC level -> mask pattern
151
	 *
152
	 * @var int[][]
153
	 */
154
	protected const formatPattern = [
155
		[ // L
156
			0b111011111000100,
157
			0b111001011110011,
158
			0b111110110101010,
159
			0b111100010011101,
160
			0b110011000101111,
161
			0b110001100011000,
162
			0b110110001000001,
163
			0b110100101110110,
164
		],
165
		[ // M
166
			0b101010000010010,
167
			0b101000100100101,
168
			0b101111001111100,
169
			0b101101101001011,
170
			0b100010111111001,
171
			0b100000011001110,
172
			0b100111110010111,
173
			0b100101010100000,
174
		],
175
		[ // Q
176
			0b011010101011111,
177
			0b011000001101000,
178
			0b011111100110001,
179
			0b011101000000110,
180
			0b010010010110100,
181
			0b010000110000011,
182
			0b010111011011010,
183
			0b010101111101101,
184
		],
185
		[ // H
186
			0b001011010001001,
187
			0b001001110111110,
188
			0b001110011100111,
189
			0b001100111010000,
190
			0b000011101100010,
191
			0b000001001010101,
192
			0b000110100001100,
193
			0b000100000111011,
194
		],
195
	];
196
197
	/**
198
	 * the current QR Code version number
199
	 */
200
	protected int $version;
201
202
	/**
203
	 * the current ECC level
204
	 */
205
	protected int $eclevel;
206
207
	/**
208
	 * the used mask pattern, set via QRMatrix::mapData()
209
	 */
210
	protected int $maskPattern = QRCode::MASK_PATTERN_AUTO;
211
212
	/**
213
	 * the size (side length) of the matrix
214
	 */
215
	protected int $moduleCount;
216
217
	/**
218
	 * the actual matrix data array
219
	 *
220
	 * @var int[][]
221
	 */
222
	protected array $matrix;
223
224
	/**
225
	 * QRMatrix constructor.
226
	 *
227
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
228
	 */
229
	public function __construct(int $version, int $eclevel){
230
231
		if(!in_array($version, range(1, 40), true)){
232
			throw new QRCodeDataException('invalid QR Code version');
233
		}
234
235
		if(!array_key_exists($eclevel, QRCode::ECC_MODES)){
236
			throw new QRCodeDataException('invalid ecc level');
237
		}
238
239
		$this->version     = $version;
240
		$this->eclevel     = $eclevel;
241
		$this->moduleCount = $this->version * 4 + 17;
242
		$this->matrix      = array_fill(0, $this->moduleCount, array_fill(0, $this->moduleCount, $this::M_NULL));
243
	}
244
245
	/**
246
	 * shortcut to initialize the matrix
247
	 */
248
	public function init(int $maskPattern, bool $test = null):QRMatrix{
249
		return $this
250
			->setFinderPattern()
251
			->setSeparators()
252
			->setAlignmentPattern()
253
			->setTimingPattern()
254
			->setVersionNumber($test)
255
			->setFormatInfo($maskPattern, $test)
256
			->setDarkModule()
257
		;
258
	}
259
260
	/**
261
	 * Returns the data matrix
262
	 *
263
	 * @return int[][]
264
	 */
265
	public function matrix():array{
266
		return $this->matrix;
267
	}
268
269
	/**
270
	 * Returns the current version number
271
	 */
272
	public function version():int{
273
		return $this->version;
274
	}
275
276
	/**
277
	 * Returns the current ECC level
278
	 */
279
	public function eccLevel():int{
280
		return $this->eclevel;
281
	}
282
283
	/**
284
	 * Returns the current mask pattern
285
	 */
286
	public function maskPattern():int{
287
		return $this->maskPattern;
288
	}
289
290
	/**
291
	 * Returns the absoulute size of the matrix, including quiet zone (after setting it).
292
	 *
293
	 * size = version * 4 + 17 [ + 2 * quietzone size]
294
	 */
295
	public function size():int{
296
		return $this->moduleCount;
297
	}
298
299
	/**
300
	 * Returns the value of the module at position [$x, $y]
301
	 */
302
	public function get(int $x, int $y):int{
303
		return $this->matrix[$y][$x];
304
	}
305
306
	/**
307
	 * Sets the $M_TYPE value for the module at position [$x, $y]
308
	 *
309
	 *   true  => $M_TYPE << 8
310
	 *   false => $M_TYPE
311
	 */
312
	public function set(int $x, int $y, bool $value, int $M_TYPE):QRMatrix{
313
		$this->matrix[$y][$x] = $M_TYPE << ($value ? 8 : 0);
314
315
		return $this;
316
	}
317
318
	/**
319
	 * Checks whether a module is true (dark) or false (light)
320
	 *
321
	 *   true  => $value >> 8 === $M_TYPE
322
	 *            $value >> 8 > 0
323
	 *
324
	 *   false => $value === $M_TYPE
325
	 *            $value >> 8 === 0
326
	 */
327
	public function check(int $x, int $y):bool{
328
		return $this->matrix[$y][$x] >> 8 > 0;
329
	}
330
331
332
	/**
333
	 * Sets the "dark module", that is always on the same position 1x1px away from the bottom left finder
334
	 */
335
	public function setDarkModule():QRMatrix{
336
		$this->set(8, 4 * $this->version + 9, true, $this::M_DARKMODULE);
337
338
		return $this;
339
	}
340
341
	/**
342
	 * Draws the 7x7 finder patterns in the corners top left/right and bottom left
343
	 *
344
	 * ISO/IEC 18004:2000 Section 7.3.2
345
	 */
346
	public function setFinderPattern():QRMatrix{
347
348
		$pos = [
349
			[0, 0], // top left
350
			[$this->moduleCount - 7, 0], // bottom left
351
			[0, $this->moduleCount - 7], // top right
352
		];
353
354
		foreach($pos as $c){
355
			for($y = 0; $y < 7; $y++){
356
				for($x = 0; $x < 7; $x++){
357
					$this->set(
358
						$c[0] + $y,
359
						$c[1] + $x,
360
						!(($x > 0 && $x < 6 && ($y === 1 || $y === 5)) || ($y > 0 && $y < 6 && ($x === 1 || $x === 5))),
361
						$this::M_FINDER
362
					);
363
				}
364
			}
365
		}
366
367
		return $this;
368
	}
369
370
	/**
371
	 * Draws the separator lines around the finder patterns
372
	 *
373
	 * ISO/IEC 18004:2000 Section 7.3.3
374
	 */
375
	public function setSeparators():QRMatrix{
376
377
		$h = [
378
			[7, 0],
379
			[$this->moduleCount - 8, 0],
380
			[7, $this->moduleCount - 8],
381
		];
382
383
		$v = [
384
			[7, 7],
385
			[$this->moduleCount - 1, 7],
386
			[7, $this->moduleCount - 8],
387
		];
388
389
		for($c = 0; $c < 3; $c++){
390
			for($i = 0; $i < 8; $i++){
391
				$this->set($h[$c][0]     , $h[$c][1] + $i, false, $this::M_SEPARATOR);
392
				$this->set($v[$c][0] - $i, $v[$c][1]     , false, $this::M_SEPARATOR);
393
			}
394
		}
395
396
		return $this;
397
	}
398
399
400
	/**
401
	 * Draws the 5x5 alignment patterns
402
	 *
403
	 * ISO/IEC 18004:2000 Section 7.3.5
404
	 */
405
	public function setAlignmentPattern():QRMatrix{
406
407
		foreach($this::alignmentPattern[$this->version] as $y){
408
			foreach($this::alignmentPattern[$this->version] as $x){
409
410
				// skip existing patterns
411
				if($this->matrix[$y][$x] !== $this::M_NULL){
412
					continue;
413
				}
414
415
				for($ry = -2; $ry <= 2; $ry++){
416
					for($rx = -2; $rx <= 2; $rx++){
417
						$v = ($ry === 0 && $rx === 0) || $ry === 2 || $ry === -2 || $rx === 2 || $rx === -2;
418
419
						$this->set($x + $rx, $y + $ry, $v, $this::M_ALIGNMENT);
420
					}
421
				}
422
423
			}
424
		}
425
426
		return $this;
427
	}
428
429
430
	/**
431
	 * Draws the timing pattern (h/v checkered line between the finder patterns)
432
	 *
433
	 * ISO/IEC 18004:2000 Section 7.3.4
434
	 */
435
	public function setTimingPattern():QRMatrix{
436
437
		foreach(range(8, $this->moduleCount - 8 - 1) as $i){
438
439
			if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
440
				continue;
441
			}
442
443
			$v = $i % 2 === 0;
444
445
			$this->set($i, 6, $v, $this::M_TIMING); // h
446
			$this->set(6, $i, $v, $this::M_TIMING); // v
447
		}
448
449
		return $this;
450
	}
451
452
	/**
453
	 * Draws the version information, 2x 3x6 pixel
454
	 *
455
	 * ISO/IEC 18004:2000 Section 8.10
456
	 */
457
	public function setVersionNumber(bool $test = null):QRMatrix{
458
		$bits = $this::versionPattern[$this->version] ?? false;
459
460
		if($bits !== false){
461
462
			for($i = 0; $i < 18; $i++){
463
				$a = (int)floor($i / 3);
464
				$b = $i % 3 + $this->moduleCount - 8 - 3;
465
				$v = !$test && (($bits >> $i) & 1) === 1;
466
467
				$this->set($b, $a, $v, $this::M_VERSION); // ne
468
				$this->set($a, $b, $v, $this::M_VERSION); // sw
469
			}
470
471
		}
472
473
		return $this;
474
	}
475
476
	/**
477
	 * Draws the format info along the finder patterns
478
	 *
479
	 * ISO/IEC 18004:2000 Section 8.9
480
	 */
481
	public function setFormatInfo(int $maskPattern, bool $test = null):QRMatrix{
482
		$bits = $this::formatPattern[QRCode::ECC_MODES[$this->eclevel]][$maskPattern] ?? 0;
483
484
		for($i = 0; $i < 15; $i++){
485
			$v = !$test && (($bits >> $i) & 1) === 1;
486
487
			if($i < 6){
488
				$this->set(8, $i, $v, $this::M_FORMAT);
489
			}
490
			elseif($i < 8){
491
				$this->set(8, $i + 1, $v, $this::M_FORMAT);
492
			}
493
			else{
494
				$this->set(8, $this->moduleCount - 15 + $i, $v, $this::M_FORMAT);
495
			}
496
497
			if($i < 8){
498
				$this->set($this->moduleCount - $i - 1, 8, $v, $this::M_FORMAT);
499
			}
500
			elseif($i < 9){
501
				$this->set(15 - $i, 8, $v, $this::M_FORMAT);
502
			}
503
			else{
504
				$this->set(15 - $i - 1, 8, $v, $this::M_FORMAT);
505
			}
506
507
		}
508
509
		$this->set(8, $this->moduleCount - 8, !$test, $this::M_FORMAT);
510
511
		return $this;
512
	}
513
514
	/**
515
	 * Draws the "quiet zone" of $size around the matrix
516
	 *
517
	 * ISO/IEC 18004:2000 Section 7.3.7
518
	 *
519
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
520
	 */
521
	public function setQuietZone(int $size = null):QRMatrix{
522
523
		if($this->matrix[$this->moduleCount - 1][$this->moduleCount - 1] === $this::M_NULL){
524
			throw new QRCodeDataException('use only after writing data');
525
		}
526
527
		$size = $size !== null
528
			? max(0, min($size, floor($this->moduleCount / 2)))
529
			: 4;
530
531
		for($y = 0; $y < $this->moduleCount; $y++){
532
			for($i = 0; $i < $size; $i++){
533
				array_unshift($this->matrix[$y], $this::M_QUIETZONE);
534
				array_push($this->matrix[$y], $this::M_QUIETZONE);
535
			}
536
		}
537
538
		$this->moduleCount += ($size * 2);
539
540
		$r = array_fill(0, $this->moduleCount, $this::M_QUIETZONE);
541
542
		for($i = 0; $i < $size; $i++){
543
			array_unshift($this->matrix, $r);
544
			array_push($this->matrix, $r);
545
		}
546
547
		return $this;
548
	}
549
550
	/**
551
	 * Maps the binary $data array from QRDataInterface::maskECC() on the matrix,
552
	 * masking the data using $maskPattern (ISO/IEC 18004:2000 Section 8.8)
553
	 *
554
	 * @see \chillerlan\QRCode\Data\QRDataAbstract::maskECC()
555
	 *
556
	 * @param int[] $data
557
	 * @param int   $maskPattern
558
	 *
559
	 * @return \chillerlan\QRCode\Data\QRMatrix
560
	 */
561
	public function mapData(array $data, int $maskPattern):QRMatrix{
562
		$this->maskPattern = $maskPattern;
563
		$byteCount         = count($data);
564
		$y                 = $this->moduleCount - 1;
565
		$inc               = -1;
566
		$byteIndex         = 0;
567
		$bitIndex          = 7;
568
		$mask              = $this->getMask($this->maskPattern);
569
570
		for($i = $y; $i > 0; $i -= 2){
571
572
			if($i === 6){
573
				$i--;
574
			}
575
576
			while(true){
577
				for($c = 0; $c < 2; $c++){
578
					$x = $i - $c;
579
580
					if($this->matrix[$y][$x] === $this::M_NULL){
581
						$v = false;
582
583
						if($byteIndex < $byteCount){
584
							$v = (($data[$byteIndex] >> $bitIndex) & 1) === 1;
585
						}
586
587
						if($mask($x, $y) === 0){
588
							$v = !$v;
589
						}
590
591
						$this->matrix[$y][$x] = $this::M_DATA << ($v ? 8 : 0);
592
						$bitIndex--;
593
594
						if($bitIndex === -1){
595
							$byteIndex++;
596
							$bitIndex = 7;
597
						}
598
599
					}
600
				}
601
602
				$y += $inc;
603
604
				if($y < 0 || $this->moduleCount <= $y){
605
					$y   -=  $inc;
606
					$inc  = -$inc;
607
608
					break;
609
				}
610
611
			}
612
		}
613
614
		return $this;
615
	}
616
617
	/**
618
	 * ISO/IEC 18004:2000 Section 8.8.1
619
	 *
620
	 * @see \chillerlan\QRCode\QRMatrix::mapData()
621
	 *
622
	 * @internal
623
	 *
624
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
625
	 */
626
	protected function getMask(int $maskPattern):Closure{
627
628
		if((0b111 & $maskPattern) !== $maskPattern){
629
			throw new QRCodeDataException('invalid mask pattern'); // @codeCoverageIgnore
630
		}
631
632
		return [
633
			0b000 => fn($x, $y):int => ($x + $y) % 2,
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ':', expecting T_DOUBLE_ARROW on line 633 at column 22
Loading history...
634
			0b001 => fn($x, $y):int => $x % 2,
635
			0b010 => fn($x, $y):int => $y % 3,
636
			0b011 => fn($x, $y):int => ($x + $y) % 3,
637
			0b100 => fn($x, $y):int => ((int)($x / 2) + (int)($y / 3)) % 2,
638
			0b101 => fn($x, $y):int => (($x * $y) % 2) + (($x * $y) % 3),
639
			0b110 => fn($x, $y):int => ((($x * $y) % 2) + (($x * $y) % 3)) % 2,
640
			0b111 => fn($x, $y):int => ((($x * $y) % 3) + (($x + $y) % 2)) % 2,
641
		][$maskPattern];
642
	}
643
644
}
645