Passed
Push — main ( 05917f...3d73fa )
by smiley
09:13
created

QRMatrix::checkTypes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 3
dl 0
loc 9
rs 10
c 0
b 0
f 0
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
11
namespace chillerlan\QRCode\Data;
12
13
use chillerlan\QRCode\Common\{EccLevel, MaskPattern, Version};
14
15
use SplFixedArray;
16
use function array_fill, array_unshift, floor, max, min, range;
17
18
/**
19
 * Holds a numerical representation of the final QR Code;
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
final class QRMatrix{
25
26
	/** @var int */
27
	public const M_NULL       = 0b000000000000;
28
	/** @var int */
29
	public const M_DARKMODULE = 0b000000000001;
30
	/** @var int */
31
	public const M_DATA       = 0b000000000010;
32
	/** @var int */
33
	public const M_FINDER     = 0b000000000100;
34
	/** @var int */
35
	public const M_SEPARATOR  = 0b000000001000;
36
	/** @var int */
37
	public const M_ALIGNMENT  = 0b000000010000;
38
	/** @var int */
39
	public const M_TIMING     = 0b000000100000;
40
	/** @var int */
41
	public const M_FORMAT     = 0b000001000000;
42
	/** @var int */
43
	public const M_VERSION    = 0b000010000000;
44
	/** @var int */
45
	public const M_QUIETZONE  = 0b000100000000;
46
	/** @var int */
47
	public const M_LOGO       = 0b001000000000;
48
	/** @var int */
49
	public const M_FINDER_DOT = 0b010000000000;
50
	/** @var int */
51
	public const M_TEST       = 0b011111111111;
52
	/** @var int */
53
	public const IS_DARK      = 0b100000000000;
54
55
	/**
56
	 * the used mask pattern, set via QRMatrix::mask()
57
	 */
58
	private ?MaskPattern $maskPattern = null;
59
60
	/**
61
	 * the size (side length) of the matrix, including quiet zone (if created)
62
	 */
63
	private int $moduleCount;
64
65
	/**
66
	 * the actual matrix data array
67
	 *
68
	 * @var int[][]
69
	 */
70
	private array $matrix;
71
72
	/**
73
	 * the current ECC level
74
	 */
75
	private EccLevel $eccLevel;
76
77
	/**
78
	 * a Version instance
79
	 */
80
	private Version $version;
81
82
	/**
83
	 * QRMatrix constructor.
84
	 */
85
	public function __construct(Version $version, EccLevel $eccLevel){
86
		$this->version     = $version;
87
		$this->eccLevel    = $eccLevel;
88
		$this->moduleCount = $this->version->getDimension();
89
		$this->matrix      = array_fill(0, $this->moduleCount, array_fill(0, $this->moduleCount, $this::M_NULL));
90
	}
91
92
	/**
93
	 * shortcut to initialize the functional patterns
94
	 */
95
	public function initFunctionalPatterns():self{
96
		return $this
97
			->setFinderPattern()
98
			->setSeparators()
99
			->setAlignmentPattern()
100
			->setTimingPattern()
101
			->setDarkModule()
102
		;
103
	}
104
105
	/**
106
	 * shortcut to set format and version info
107
	 */
108
	public function initFormatInfo(MaskPattern $maskPattern):self{
109
		return $this
110
			->setVersionNumber()
111
			->setFormatInfo($maskPattern)
112
		;
113
	}
114
115
	/**
116
	 * Returns the data matrix, returns a pure boolean representation if $boolean is set to true
117
	 *
118
	 * @return int[][]|bool[][]
119
	 */
120
	public function matrix(bool $boolean = false):array{
121
122
		if(!$boolean){
123
			return $this->matrix;
124
		}
125
126
		$matrix = [];
127
128
		foreach($this->matrix as $y => $row){
129
			$matrix[$y] = [];
130
131
			foreach($row as $x => $val){
132
				$matrix[$y][$x] = ($val & $this::IS_DARK) === $this::IS_DARK;
133
			}
134
		}
135
136
		return $matrix;
137
	}
138
139
	/**
140
	 * Returns the current version number
141
	 */
142
	public function version():Version{
143
		return $this->version;
144
	}
145
146
	/**
147
	 * Returns the current ECC level
148
	 */
149
	public function eccLevel():EccLevel{
150
		return $this->eccLevel;
151
	}
152
153
	/**
154
	 * Returns the current mask pattern
155
	 */
156
	public function maskPattern():?MaskPattern{
157
		return $this->maskPattern;
158
	}
159
160
	/**
161
	 * Returns the absoulute size of the matrix, including quiet zone (after setting it).
162
	 *
163
	 * size = version * 4 + 17 [ + 2 * quietzone size]
164
	 */
165
	public function size():int{
166
		return $this->moduleCount;
167
	}
168
169
	/**
170
	 * Returns the value of the module at position [$x, $y]
171
	 */
172
	public function get(int $x, int $y):int{
173
		return $this->matrix[$y][$x];
174
	}
175
176
	/**
177
	 * Sets the $M_TYPE value for the module at position [$x, $y]
178
	 *
179
	 *   true  => $M_TYPE | 0x800
180
	 *   false => $M_TYPE
181
	 */
182
	public function set(int $x, int $y, bool $value, int $M_TYPE):self{
183
		$this->matrix[$y][$x] = $M_TYPE | ($value ? $this::IS_DARK : 0);
184
185
		return $this;
186
	}
187
188
	/**
189
	 * Flips the value of the module
190
	 */
191
	public function flip(int $x, int $y):self{
192
		$this->matrix[$y][$x] ^= $this::IS_DARK;
193
194
		return $this;
195
	}
196
197
	/**
198
	 * Checks whether a module is of the given $M_TYPE
199
	 *
200
	 *   true => $value & $M_TYPE === $M_TYPE
201
	 */
202
	public function checkType(int $x, int $y, int $M_TYPE):bool{
203
		return ($this->matrix[$y][$x] & $M_TYPE) === $M_TYPE;
204
	}
205
206
	/**
207
	 * checks whether a module matches one of the given $M_TYPES
208
	 */
209
	public function checkTypes(int $x, int $y, array $M_TYPES):bool{
210
211
		foreach($M_TYPES as $type){
212
			if($this->checkType($x, $y, $type)){
213
				return true;
214
			}
215
		}
216
217
		return false;
218
	}
219
220
	/**
221
	 * Checks whether a module is true (dark) or false (light)
222
	 *
223
	 *   true  => $value & 0x800 === 0x800
224
	 *   false => $value & 0x800 === 0
225
	 */
226
	public function check(int $x, int $y):bool{
227
		return $this->checkType($x, $y, $this::IS_DARK);
228
	}
229
230
	/**
231
	 * Sets the "dark module", that is always on the same position 1x1px away from the bottom left finder
232
	 *
233
	 * 4 * version + 9 or moduleCount - 8
234
	 */
235
	public function setDarkModule():self{
236
		$this->set(8, $this->moduleCount - 8, true, $this::M_DARKMODULE);
237
238
		return $this;
239
	}
240
241
	/**
242
	 * Draws the 7x7 finder patterns in the corners top left/right and bottom left
243
	 *
244
	 * ISO/IEC 18004:2000 Section 7.3.2
245
	 */
246
	public function setFinderPattern():self{
247
248
		$pos = [
249
			[0, 0], // top left
250
			[$this->moduleCount - 7, 0], // bottom left
251
			[0, $this->moduleCount - 7], // top right
252
		];
253
254
		foreach($pos as $c){
255
			for($y = 0; $y < 7; $y++){
256
				for($x = 0; $x < 7; $x++){
257
					// outer (dark) 7*7 square
258
					if($x === 0 || $x === 6 || $y === 0 || $y === 6){
259
						$this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER);
260
					}
261
					// inner (light) 5*5 square
262
					elseif($x === 1 || $x === 5 || $y === 1 || $y === 5){
263
						$this->set($c[0] + $y, $c[1] + $x, false, $this::M_FINDER);
264
					}
265
					// 3*3 dot
266
					else{
267
						$this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER_DOT);
268
					}
269
				}
270
			}
271
		}
272
273
		return $this;
274
	}
275
276
	/**
277
	 * Draws the separator lines around the finder patterns
278
	 *
279
	 * ISO/IEC 18004:2000 Section 7.3.3
280
	 */
281
	public function setSeparators():self{
282
283
		$h = [
284
			[7, 0],
285
			[$this->moduleCount - 8, 0],
286
			[7, $this->moduleCount - 8],
287
		];
288
289
		$v = [
290
			[7, 7],
291
			[$this->moduleCount - 1, 7],
292
			[7, $this->moduleCount - 8],
293
		];
294
295
		for($c = 0; $c < 3; $c++){
296
			for($i = 0; $i < 8; $i++){
297
				$this->set($h[$c][0]     , $h[$c][1] + $i, false, $this::M_SEPARATOR);
298
				$this->set($v[$c][0] - $i, $v[$c][1]     , false, $this::M_SEPARATOR);
299
			}
300
		}
301
302
		return $this;
303
	}
304
305
306
	/**
307
	 * Draws the 5x5 alignment patterns
308
	 *
309
	 * ISO/IEC 18004:2000 Section 7.3.5
310
	 */
311
	public function setAlignmentPattern():self{
312
		$alignmentPattern = $this->version->getAlignmentPattern();
313
314
		foreach($alignmentPattern as $y){
315
			foreach($alignmentPattern as $x){
316
317
				// skip existing patterns
318
				if($this->matrix[$y][$x] !== $this::M_NULL){
319
					continue;
320
				}
321
322
				for($ry = -2; $ry <= 2; $ry++){
323
					for($rx = -2; $rx <= 2; $rx++){
324
						$v = ($ry === 0 && $rx === 0) || $ry === 2 || $ry === -2 || $rx === 2 || $rx === -2;
325
326
						$this->set($x + $rx, $y + $ry, $v, $this::M_ALIGNMENT);
327
					}
328
				}
329
330
			}
331
		}
332
333
		return $this;
334
	}
335
336
337
	/**
338
	 * Draws the timing pattern (h/v checkered line between the finder patterns)
339
	 *
340
	 * ISO/IEC 18004:2000 Section 7.3.4
341
	 */
342
	public function setTimingPattern():self{
343
344
		foreach(range(8, $this->moduleCount - 8 - 1) as $i){
345
346
			if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
347
				continue;
348
			}
349
350
			$v = $i % 2 === 0;
351
352
			$this->set($i, 6, $v, $this::M_TIMING); // h
353
			$this->set(6, $i, $v, $this::M_TIMING); // v
354
		}
355
356
		return $this;
357
	}
358
359
	/**
360
	 * Draws the version information, 2x 3x6 pixel
361
	 *
362
	 * ISO/IEC 18004:2000 Section 8.10
363
	 */
364
	public function setVersionNumber():self{
365
		$bits = $this->version->getVersionPattern();
366
367
		if($bits !== null){
368
369
			for($i = 0; $i < 18; $i++){
370
				$a = (int)($i / 3);
371
				$b = $i % 3 + $this->moduleCount - 8 - 3;
372
				$v = (($bits >> $i) & 1) === 1;
373
374
				$this->set($b, $a, $v, $this::M_VERSION); // ne
375
				$this->set($a, $b, $v, $this::M_VERSION); // sw
376
			}
377
378
		}
379
380
		return $this;
381
	}
382
383
	/**
384
	 * Draws the format info along the finder patterns
385
	 *
386
	 * ISO/IEC 18004:2000 Section 8.9
387
	 */
388
	public function setFormatInfo(MaskPattern $maskPattern):self{
389
		$bits = $this->eccLevel->getformatPattern($maskPattern);
390
391
		for($i = 0; $i < 15; $i++){
392
			$v = (($bits >> $i) & 1) === 1;
393
394
			if($i < 6){
395
				$this->set(8, $i, $v, $this::M_FORMAT);
396
			}
397
			elseif($i < 8){
398
				$this->set(8, $i + 1, $v, $this::M_FORMAT);
399
			}
400
			else{
401
				$this->set(8, $this->moduleCount - 15 + $i, $v, $this::M_FORMAT);
402
			}
403
404
			if($i < 8){
405
				$this->set($this->moduleCount - $i - 1, 8, $v, $this::M_FORMAT);
406
			}
407
			elseif($i < 9){
408
				$this->set(15 - $i, 8, $v, $this::M_FORMAT);
409
			}
410
			else{
411
				$this->set(15 - $i - 1, 8, $v, $this::M_FORMAT);
412
			}
413
414
		}
415
416
		return $this;
417
	}
418
419
	/**
420
	 * Draws the "quiet zone" of $size around the matrix
421
	 *
422
	 * ISO/IEC 18004:2000 Section 7.3.7
423
	 *
424
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
425
	 */
426
	public function setQuietZone(int $size = null):self{
427
428
		if($this->matrix[$this->moduleCount - 1][$this->moduleCount - 1] === $this::M_NULL){
429
			throw new QRCodeDataException('use only after writing data');
430
		}
431
432
		$size = $size !== null
433
			? max(0, min($size, floor($this->moduleCount / 2)))
434
			: 4;
435
436
		for($y = 0; $y < $this->moduleCount; $y++){
437
			for($i = 0; $i < $size; $i++){
438
				array_unshift($this->matrix[$y], $this::M_QUIETZONE);
439
				$this->matrix[$y][] = $this::M_QUIETZONE;
440
			}
441
		}
442
443
		$this->moduleCount += ($size * 2);
444
445
		$r = array_fill(0, $this->moduleCount, $this::M_QUIETZONE);
446
447
		for($i = 0; $i < $size; $i++){
448
			array_unshift($this->matrix, $r);
449
			$this->matrix[] = $r;
450
		}
451
452
		return $this;
453
	}
454
455
	/**
456
	 * Clears a space of $width * $height in order to add a logo or text.
457
	 *
458
	 * Additionally, the logo space can be positioned within the QR Code - respecting the main functional patterns -
459
	 * using $startX and $startY. If either of these are null, the logo space will be centered in that direction.
460
	 * ECC level "H" (30%) is required.
461
	 *
462
	 * Please note that adding a logo space minimizes the error correction capacity of the QR Code and
463
	 * created images may become unreadable, especially when printed with a chance to receive damage.
464
	 * Please test thoroughly before using this feature in production.
465
	 *
466
	 * This method should be called from within an output module (after the matrix has been filled with data).
467
	 * Note that there is no restiction on how many times this method could be called on the same matrix instance.
468
	 *
469
	 * @link https://github.com/chillerlan/php-qrcode/issues/52
470
	 *
471
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
472
	 */
473
	public function setLogoSpace(int $width, int $height, int $startX = null, int $startY = null):self{
474
475
		// for logos we operate in ECC H (30%) only
476
		if($this->eccLevel->getLevel() !== EccLevel::H){
477
			throw new QRCodeDataException('ECC level "H" required to add logo space');
478
		}
479
480
		// we need uneven sizes to center the logo space, adjust if needed
481
		if($startX === null && ($width % 2) === 0){
482
			$width++;
483
		}
484
485
		if($startY === null && ($height % 2) === 0){
486
			$height++;
487
		}
488
489
		// $this->moduleCount includes the quiet zone (if created), we need the QR size here
490
		$length = $this->version->getDimension();
491
492
		// throw if the logo space exceeds the maximum error correction capacity
493
		if($width * $height > floor($length * $length * 0.2)){
494
			throw new QRCodeDataException('logo space exceeds the maximum error correction capacity');
495
		}
496
497
		// quiet zone size
498
		$qz    = ($this->moduleCount - $length) / 2;
499
		// skip quiet zone and the first 9 rows/columns (finder-, mode-, version- and timing patterns)
500
		$start = $qz + 9;
501
		// skip quiet zone
502
		$end   = $this->moduleCount - $qz;
503
504
		// determine start coordinates
505
		$startX = ($startX !== null ? $startX : ($length - $width) / 2) + $qz;
506
		$startY = ($startY !== null ? $startY : ($length - $height) / 2) + $qz;
507
508
		// clear the space
509
		foreach($this->matrix as $y => $row){
510
			foreach($row as $x => $val){
511
				// out of bounds, skip
512
				if($x < $start || $y < $start ||$x >= $end || $y >= $end){
513
					continue;
514
				}
515
				// a match
516
				if($x >= $startX && $x < ($startX + $width) && $y >= $startY && $y < ($startY + $height)){
517
					$this->set($x, $y, false, $this::M_LOGO);
518
				}
519
			}
520
		}
521
522
		return $this;
523
	}
524
525
	/**
526
	 * Maps the binary $data array from QRData::maskECC() on the matrix,
527
	 * masking the data using $maskPattern (ISO/IEC 18004:2000 Section 8.8)
528
	 *
529
	 * @see \chillerlan\QRCode\Data\QRData::maskECC()
530
	 *
531
	 * @param \SplFixedArray<int> $data
532
	 *
533
	 * @return \chillerlan\QRCode\Data\QRMatrix
534
	 */
535
	public function mapData(SplFixedArray $data):self{
536
		$byteCount         = $data->count();
537
		$y                 = $this->moduleCount - 1;
538
		$inc               = -1;
539
		$byteIndex         = 0;
540
		$bitIndex          = 7;
541
542
		for($i = $y; $i > 0; $i -= 2){
543
544
			if($i === 6){
545
				$i--;
546
			}
547
548
			while(true){
549
				for($c = 0; $c < 2; $c++){
550
					$x = $i - $c;
551
552
					if($this->matrix[$y][$x] !== $this::M_NULL){
553
						continue;
554
					}
555
556
					$v = false;
557
558
					if($byteIndex < $byteCount){
559
						$v = (($data[$byteIndex] >> $bitIndex) & 1) === 1;
560
					}
561
562
					$this->matrix[$y][$x] = $this::M_DATA | ($v ? $this::IS_DARK : 0);
563
					$bitIndex--;
564
565
					if($bitIndex === -1){
566
						$byteIndex++;
567
						$bitIndex = 7;
568
					}
569
570
				}
571
572
				$y += $inc;
573
574
				if($y < 0 || $this->moduleCount <= $y){
575
					$y   -=  $inc;
576
					$inc  = -$inc;
577
578
					break;
579
				}
580
581
			}
582
		}
583
584
		return $this;
585
	}
586
587
	/**
588
	 * Applies the mask pattern
589
	 *
590
	 * ISO/IEC 18004:2000 Section 8.8.1
591
	 */
592
	public function mask(MaskPattern $maskPattern):self{
593
		$this->maskPattern = $maskPattern;
594
		$mask              = $this->maskPattern->getMask();
595
596
		foreach($this->matrix as $y => &$row){
597
			foreach($row as $x => &$val){
598
				if($mask($x, $y) && ($val & $this::M_DATA) === $this::M_DATA){
599
					$val ^= $this::IS_DARK;
600
				}
601
			}
602
		}
603
604
		return $this;
605
	}
606
607
}
608