Passed
Push — main ( 48b6c2...5c2c92 )
by smiley
02:24
created

QRMatrix::maskPattern()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 2
rs 10
c 1
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 is true (dark) or false (light)
208
	 *
209
	 *   true  => $value & 0x800 === 0x800
210
	 *   false => $value & 0x800 === 0
211
	 */
212
	public function check(int $x, int $y):bool{
213
		return $this->checkType($x, $y, $this::IS_DARK);
214
	}
215
216
	/**
217
	 * Sets the "dark module", that is always on the same position 1x1px away from the bottom left finder
218
	 *
219
	 * 4 * version + 9 or moduleCount - 8
220
	 */
221
	public function setDarkModule():self{
222
		$this->set(8, $this->moduleCount - 8, true, $this::M_DARKMODULE);
223
224
		return $this;
225
	}
226
227
	/**
228
	 * Draws the 7x7 finder patterns in the corners top left/right and bottom left
229
	 *
230
	 * ISO/IEC 18004:2000 Section 7.3.2
231
	 */
232
	public function setFinderPattern():self{
233
234
		$pos = [
235
			[0, 0], // top left
236
			[$this->moduleCount - 7, 0], // bottom left
237
			[0, $this->moduleCount - 7], // top right
238
		];
239
240
		foreach($pos as $c){
241
			for($y = 0; $y < 7; $y++){
242
				for($x = 0; $x < 7; $x++){
243
					// outer (dark) 7*7 square
244
					if($x === 0 || $x === 6 || $y === 0 || $y === 6){
245
						$this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER);
246
					}
247
					// inner (light) 5*5 square
248
					elseif($x === 1 || $x === 5 || $y === 1 || $y === 5){
249
						$this->set($c[0] + $y, $c[1] + $x, false, $this::M_FINDER);
250
					}
251
					// 3*3 dot
252
					else{
253
						$this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER_DOT);
254
					}
255
				}
256
			}
257
		}
258
259
		return $this;
260
	}
261
262
	/**
263
	 * Draws the separator lines around the finder patterns
264
	 *
265
	 * ISO/IEC 18004:2000 Section 7.3.3
266
	 */
267
	public function setSeparators():self{
268
269
		$h = [
270
			[7, 0],
271
			[$this->moduleCount - 8, 0],
272
			[7, $this->moduleCount - 8],
273
		];
274
275
		$v = [
276
			[7, 7],
277
			[$this->moduleCount - 1, 7],
278
			[7, $this->moduleCount - 8],
279
		];
280
281
		for($c = 0; $c < 3; $c++){
282
			for($i = 0; $i < 8; $i++){
283
				$this->set($h[$c][0]     , $h[$c][1] + $i, false, $this::M_SEPARATOR);
284
				$this->set($v[$c][0] - $i, $v[$c][1]     , false, $this::M_SEPARATOR);
285
			}
286
		}
287
288
		return $this;
289
	}
290
291
292
	/**
293
	 * Draws the 5x5 alignment patterns
294
	 *
295
	 * ISO/IEC 18004:2000 Section 7.3.5
296
	 */
297
	public function setAlignmentPattern():self{
298
		$alignmentPattern = $this->version->getAlignmentPattern();
299
300
		foreach($alignmentPattern as $y){
301
			foreach($alignmentPattern as $x){
302
303
				// skip existing patterns
304
				if($this->matrix[$y][$x] !== $this::M_NULL){
305
					continue;
306
				}
307
308
				for($ry = -2; $ry <= 2; $ry++){
309
					for($rx = -2; $rx <= 2; $rx++){
310
						$v = ($ry === 0 && $rx === 0) || $ry === 2 || $ry === -2 || $rx === 2 || $rx === -2;
311
312
						$this->set($x + $rx, $y + $ry, $v, $this::M_ALIGNMENT);
313
					}
314
				}
315
316
			}
317
		}
318
319
		return $this;
320
	}
321
322
323
	/**
324
	 * Draws the timing pattern (h/v checkered line between the finder patterns)
325
	 *
326
	 * ISO/IEC 18004:2000 Section 7.3.4
327
	 */
328
	public function setTimingPattern():self{
329
330
		foreach(range(8, $this->moduleCount - 8 - 1) as $i){
331
332
			if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
333
				continue;
334
			}
335
336
			$v = $i % 2 === 0;
337
338
			$this->set($i, 6, $v, $this::M_TIMING); // h
339
			$this->set(6, $i, $v, $this::M_TIMING); // v
340
		}
341
342
		return $this;
343
	}
344
345
	/**
346
	 * Draws the version information, 2x 3x6 pixel
347
	 *
348
	 * ISO/IEC 18004:2000 Section 8.10
349
	 */
350
	public function setVersionNumber():self{
351
		$bits = $this->version->getVersionPattern();
352
353
		if($bits !== null){
354
355
			for($i = 0; $i < 18; $i++){
356
				$a = (int)($i / 3);
357
				$b = $i % 3 + $this->moduleCount - 8 - 3;
358
				$v = (($bits >> $i) & 1) === 1;
359
360
				$this->set($b, $a, $v, $this::M_VERSION); // ne
361
				$this->set($a, $b, $v, $this::M_VERSION); // sw
362
			}
363
364
		}
365
366
		return $this;
367
	}
368
369
	/**
370
	 * Draws the format info along the finder patterns
371
	 *
372
	 * ISO/IEC 18004:2000 Section 8.9
373
	 */
374
	public function setFormatInfo(MaskPattern $maskPattern):self{
375
		$bits = $this->eccLevel->getformatPattern($maskPattern);
376
377
		for($i = 0; $i < 15; $i++){
378
			$v = (($bits >> $i) & 1) === 1;
379
380
			if($i < 6){
381
				$this->set(8, $i, $v, $this::M_FORMAT);
382
			}
383
			elseif($i < 8){
384
				$this->set(8, $i + 1, $v, $this::M_FORMAT);
385
			}
386
			else{
387
				$this->set(8, $this->moduleCount - 15 + $i, $v, $this::M_FORMAT);
388
			}
389
390
			if($i < 8){
391
				$this->set($this->moduleCount - $i - 1, 8, $v, $this::M_FORMAT);
392
			}
393
			elseif($i < 9){
394
				$this->set(15 - $i, 8, $v, $this::M_FORMAT);
395
			}
396
			else{
397
				$this->set(15 - $i - 1, 8, $v, $this::M_FORMAT);
398
			}
399
400
		}
401
402
		return $this;
403
	}
404
405
	/**
406
	 * Draws the "quiet zone" of $size around the matrix
407
	 *
408
	 * ISO/IEC 18004:2000 Section 7.3.7
409
	 *
410
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
411
	 */
412
	public function setQuietZone(int $size = null):self{
413
414
		if($this->matrix[$this->moduleCount - 1][$this->moduleCount - 1] === $this::M_NULL){
415
			throw new QRCodeDataException('use only after writing data');
416
		}
417
418
		$size = $size !== null
419
			? max(0, min($size, floor($this->moduleCount / 2)))
420
			: 4;
421
422
		for($y = 0; $y < $this->moduleCount; $y++){
423
			for($i = 0; $i < $size; $i++){
424
				array_unshift($this->matrix[$y], $this::M_QUIETZONE);
425
				$this->matrix[$y][] = $this::M_QUIETZONE;
426
			}
427
		}
428
429
		$this->moduleCount += ($size * 2);
430
431
		$r = array_fill(0, $this->moduleCount, $this::M_QUIETZONE);
432
433
		for($i = 0; $i < $size; $i++){
434
			array_unshift($this->matrix, $r);
435
			$this->matrix[] = $r;
436
		}
437
438
		return $this;
439
	}
440
441
	/**
442
	 * Clears a space of $width * $height in order to add a logo or text.
443
	 *
444
	 * Additionally, the logo space can be positioned within the QR Code - respecting the main functional patterns -
445
	 * using $startX and $startY. If either of these are null, the logo space will be centered in that direction.
446
	 * ECC level "H" (30%) is required.
447
	 *
448
	 * Please note that adding a logo space minimizes the error correction capacity of the QR Code and
449
	 * created images may become unreadable, especially when printed with a chance to receive damage.
450
	 * Please test thoroughly before using this feature in production.
451
	 *
452
	 * This method should be called from within an output module (after the matrix has been filled with data).
453
	 * Note that there is no restiction on how many times this method could be called on the same matrix instance.
454
	 *
455
	 * @link https://github.com/chillerlan/php-qrcode/issues/52
456
	 *
457
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
458
	 */
459
	public function setLogoSpace(int $width, int $height, int $startX = null, int $startY = null):self{
460
461
		// for logos we operate in ECC H (30%) only
462
		if($this->eccLevel->getLevel() !== EccLevel::H){
463
			throw new QRCodeDataException('ECC level "H" required to add logo space');
464
		}
465
466
		// we need uneven sizes to center the logo space, adjust if needed
467
		if($startX === null && ($width % 2) === 0){
468
			$width++;
469
		}
470
471
		if($startY === null && ($height % 2) === 0){
472
			$height++;
473
		}
474
475
		// $this->moduleCount includes the quiet zone (if created), we need the QR size here
476
		$length = $this->version->getDimension();
477
478
		// throw if the logo space exceeds the maximum error correction capacity
479
		if($width * $height > floor($length * $length * 0.2)){
480
			throw new QRCodeDataException('logo space exceeds the maximum error correction capacity');
481
		}
482
483
		// quiet zone size
484
		$qz    = ($this->moduleCount - $length) / 2;
485
		// skip quiet zone and the first 9 rows/columns (finder-, mode-, version- and timing patterns)
486
		$start = $qz + 9;
487
		// skip quiet zone
488
		$end   = $this->moduleCount - $qz;
489
490
		// determine start coordinates
491
		$startX = ($startX !== null ? $startX : ($length - $width) / 2) + $qz;
492
		$startY = ($startY !== null ? $startY : ($length - $height) / 2) + $qz;
493
494
		// clear the space
495
		foreach($this->matrix as $y => $row){
496
			foreach($row as $x => $val){
497
				// out of bounds, skip
498
				if($x < $start || $y < $start ||$x >= $end || $y >= $end){
499
					continue;
500
				}
501
				// a match
502
				if($x >= $startX && $x < ($startX + $width) && $y >= $startY && $y < ($startY + $height)){
503
					$this->set($x, $y, false, $this::M_LOGO);
504
				}
505
			}
506
		}
507
508
		return $this;
509
	}
510
511
	/**
512
	 * Maps the binary $data array from QRData::maskECC() on the matrix,
513
	 * masking the data using $maskPattern (ISO/IEC 18004:2000 Section 8.8)
514
	 *
515
	 * @see \chillerlan\QRCode\Data\QRData::maskECC()
516
	 *
517
	 * @param \SplFixedArray<int> $data
518
	 *
519
	 * @return \chillerlan\QRCode\Data\QRMatrix
520
	 */
521
	public function mapData(SplFixedArray $data):self{
522
		$byteCount         = $data->count();
523
		$y                 = $this->moduleCount - 1;
524
		$inc               = -1;
525
		$byteIndex         = 0;
526
		$bitIndex          = 7;
527
528
		for($i = $y; $i > 0; $i -= 2){
529
530
			if($i === 6){
531
				$i--;
532
			}
533
534
			while(true){
535
				for($c = 0; $c < 2; $c++){
536
					$x = $i - $c;
537
538
					if($this->matrix[$y][$x] !== $this::M_NULL){
539
						continue;
540
					}
541
542
					$v = false;
543
544
					if($byteIndex < $byteCount){
545
						$v = (($data[$byteIndex] >> $bitIndex) & 1) === 1;
546
					}
547
548
					$this->matrix[$y][$x] = $this::M_DATA | ($v ? $this::IS_DARK : 0);
549
					$bitIndex--;
550
551
					if($bitIndex === -1){
552
						$byteIndex++;
553
						$bitIndex = 7;
554
					}
555
556
				}
557
558
				$y += $inc;
559
560
				if($y < 0 || $this->moduleCount <= $y){
561
					$y   -=  $inc;
562
					$inc  = -$inc;
563
564
					break;
565
				}
566
567
			}
568
		}
569
570
		return $this;
571
	}
572
573
	/**
574
	 * Applies the mask pattern
575
	 *
576
	 * ISO/IEC 18004:2000 Section 8.8.1
577
	 */
578
	public function mask(MaskPattern $maskPattern):self{
579
		$this->maskPattern = $maskPattern;
580
		$mask              = $this->maskPattern->getMask();
581
582
		foreach($this->matrix as $y => &$row){
583
			foreach($row as $x => &$val){
584
				if($mask($x, $y) && ($val & $this::M_DATA) === $this::M_DATA){
585
					$val ^= $this::IS_DARK;
586
				}
587
			}
588
		}
589
590
		return $this;
591
	}
592
593
}
594