Passed
Push — v5 ( 92f563...26536d )
by smiley
02:19
created

QRMatrix::version()   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
 * @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\Common\{EccLevel, Version};
16
use chillerlan\QRCode\QRCode;
17
use Closure;
18
19
use SplFixedArray;
20
use function array_fill, array_push, array_unshift, count, floor, max, min, range;
21
22
/**
23
 * Holds a numerical representation of the final QR Code;
24
 * maps the ECC coded binary data and applies the mask pattern
25
 *
26
 * @see http://www.thonky.com/qr-code-tutorial/format-version-information
27
 */
28
final class QRMatrix{
29
30
	/** @var int */
31
	public const M_NULL       = 0x00;
32
	/** @var int */
33
	public const M_DARKMODULE = 0x02;
34
	/** @var int */
35
	public const M_DATA       = 0x04;
36
	/** @var int */
37
	public const M_FINDER     = 0x06;
38
	/** @var int */
39
	public const M_SEPARATOR  = 0x08;
40
	/** @var int */
41
	public const M_ALIGNMENT  = 0x0a;
42
	/** @var int */
43
	public const M_TIMING     = 0x0c;
44
	/** @var int */
45
	public const M_FORMAT     = 0x0e;
46
	/** @var int */
47
	public const M_VERSION    = 0x10;
48
	/** @var int */
49
	public const M_QUIETZONE  = 0x12;
50
	/** @var int */
51
	public const M_LOGO       = 0x14;
52
	/** @var int */
53
	public const M_FINDER_DOT = 0x16;
54
	/** @var int */
55
	public const M_TEST       = 0xff;
56
57
	/**
58
	 * the used mask pattern, set via QRMatrix::mapData()
59
	 */
60
	protected int $maskPattern = QRCode::MASK_PATTERN_AUTO;
61
62
	/**
63
	 * the size (side length) of the matrix, including quiet zone (if created)
64
	 */
65
	protected int $moduleCount;
66
67
	/**
68
	 * the actual matrix data array
69
	 *
70
	 * @var int[][]
71
	 */
72
	protected array $matrix;
73
74
	/**
75
	 * the current ECC level
76
	 */
77
	protected EccLevel $eccLevel;
78
79
	/**
80
	 * a Version instance
81
	 */
82
	protected Version $version;
83
84
	/**
85
	 * QRMatrix constructor.
86
	 */
87
	public function __construct(Version $version, EccLevel $eccLevel){
88
		$this->version     = $version;
89
		$this->eccLevel    = $eccLevel;
90
		$this->moduleCount = $this->version->getDimension();
91
		$this->matrix      = array_fill(0, $this->moduleCount, array_fill(0, $this->moduleCount, $this::M_NULL));
92
	}
93
94
	/**
95
	 * shortcut to initialize the matrix
96
	 */
97
	public function init(int $maskPattern, bool $test = null):QRMatrix{
98
		return $this
99
			->setFinderPattern()
100
			->setSeparators()
101
			->setAlignmentPattern()
102
			->setTimingPattern()
103
			->setVersionNumber($test)
104
			->setFormatInfo($maskPattern, $test)
105
			->setDarkModule()
106
		;
107
	}
108
109
	/**
110
	 * Returns the data matrix, returns a pure boolean representation if $boolean is set to true
111
	 *
112
	 * @return int[][]|bool[][]
113
	 */
114
	public function matrix(bool $boolean = false):array{
115
116
		if(!$boolean){
117
			return $this->matrix;
118
		}
119
120
		$matrix = [];
121
122
		foreach($this->matrix as $y => $row){
123
			$matrix[$y] = [];
124
125
			foreach($row as $x => $val){
126
				$matrix[$y][$x] = ($val >> 8) > 0;
127
			}
128
		}
129
130
		return $matrix;
131
	}
132
133
	/**
134
	 * Returns the current version number
135
	 */
136
	public function version():Version{
137
		return $this->version;
138
	}
139
140
	/**
141
	 * Returns the current ECC level
142
	 */
143
	public function eccLevel():EccLevel{
144
		return $this->eccLevel;
145
	}
146
147
	/**
148
	 * Returns the current mask pattern
149
	 */
150
	public function maskPattern():int{
151
		return $this->maskPattern;
152
	}
153
154
	/**
155
	 * Returns the absoulute size of the matrix, including quiet zone (after setting it).
156
	 *
157
	 * size = version * 4 + 17 [ + 2 * quietzone size]
158
	 */
159
	public function size():int{
160
		return $this->moduleCount;
161
	}
162
163
	/**
164
	 * Returns the value of the module at position [$x, $y]
165
	 */
166
	public function get(int $x, int $y):int{
167
		return $this->matrix[$y][$x];
168
	}
169
170
	/**
171
	 * Sets the $M_TYPE value for the module at position [$x, $y]
172
	 *
173
	 *   true  => $M_TYPE << 8
174
	 *   false => $M_TYPE
175
	 */
176
	public function set(int $x, int $y, bool $value, int $M_TYPE):QRMatrix{
177
		$this->matrix[$y][$x] = $M_TYPE << ($value ? 8 : 0);
178
179
		return $this;
180
	}
181
182
	/**
183
	 * Checks whether a module is true (dark) or false (light)
184
	 *
185
	 *   true  => $value >> 8 === $M_TYPE
186
	 *            $value >> 8 > 0
187
	 *
188
	 *   false => $value === $M_TYPE
189
	 *            $value >> 8 === 0
190
	 */
191
	public function check(int $x, int $y):bool{
192
		return ($this->matrix[$y][$x] >> 8) > 0;
193
	}
194
195
196
	/**
197
	 * Sets the "dark module", that is always on the same position 1x1px away from the bottom left finder
198
	 */
199
	public function setDarkModule():QRMatrix{
200
		$this->set(8, 4 * $this->version->getVersionNumber() + 9, true, $this::M_DARKMODULE);
201
202
		return $this;
203
	}
204
205
	/**
206
	 * Draws the 7x7 finder patterns in the corners top left/right and bottom left
207
	 *
208
	 * ISO/IEC 18004:2000 Section 7.3.2
209
	 */
210
	public function setFinderPattern():QRMatrix{
211
212
		$pos = [
213
			[0, 0], // top left
214
			[$this->moduleCount - 7, 0], // bottom left
215
			[0, $this->moduleCount - 7], // top right
216
		];
217
218
		foreach($pos as $c){
219
			for($y = 0; $y < 7; $y++){
220
				for($x = 0; $x < 7; $x++){
221
					// outer (dark) 7*7 square
222
					if($x === 0 || $x === 6 || $y === 0 || $y === 6){
223
						$this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER);
224
					}
225
					// inner (light) 5*5 square
226
					elseif($x === 1 || $x === 5 || $y === 1 || $y === 5){
227
						$this->set($c[0] + $y, $c[1] + $x, false, $this::M_FINDER);
228
					}
229
					// 3*3 dot
230
					else{
231
						$this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER_DOT);
232
					}
233
				}
234
			}
235
		}
236
237
		return $this;
238
	}
239
240
	/**
241
	 * Draws the separator lines around the finder patterns
242
	 *
243
	 * ISO/IEC 18004:2000 Section 7.3.3
244
	 */
245
	public function setSeparators():QRMatrix{
246
247
		$h = [
248
			[7, 0],
249
			[$this->moduleCount - 8, 0],
250
			[7, $this->moduleCount - 8],
251
		];
252
253
		$v = [
254
			[7, 7],
255
			[$this->moduleCount - 1, 7],
256
			[7, $this->moduleCount - 8],
257
		];
258
259
		for($c = 0; $c < 3; $c++){
260
			for($i = 0; $i < 8; $i++){
261
				$this->set($h[$c][0]     , $h[$c][1] + $i, false, $this::M_SEPARATOR);
262
				$this->set($v[$c][0] - $i, $v[$c][1]     , false, $this::M_SEPARATOR);
263
			}
264
		}
265
266
		return $this;
267
	}
268
269
270
	/**
271
	 * Draws the 5x5 alignment patterns
272
	 *
273
	 * ISO/IEC 18004:2000 Section 7.3.5
274
	 */
275
	public function setAlignmentPattern():QRMatrix{
276
		$alignmentPattern = $this->version->getAlignmentPattern();
277
278
		foreach($alignmentPattern as $y){
279
			foreach($alignmentPattern as $x){
280
281
				// skip existing patterns
282
				if($this->matrix[$y][$x] !== $this::M_NULL){
283
					continue;
284
				}
285
286
				for($ry = -2; $ry <= 2; $ry++){
287
					for($rx = -2; $rx <= 2; $rx++){
288
						$v = ($ry === 0 && $rx === 0) || $ry === 2 || $ry === -2 || $rx === 2 || $rx === -2;
289
290
						$this->set($x + $rx, $y + $ry, $v, $this::M_ALIGNMENT);
291
					}
292
				}
293
294
			}
295
		}
296
297
		return $this;
298
	}
299
300
301
	/**
302
	 * Draws the timing pattern (h/v checkered line between the finder patterns)
303
	 *
304
	 * ISO/IEC 18004:2000 Section 7.3.4
305
	 */
306
	public function setTimingPattern():QRMatrix{
307
308
		foreach(range(8, $this->moduleCount - 8 - 1) as $i){
309
310
			if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
311
				continue;
312
			}
313
314
			$v = $i % 2 === 0;
315
316
			$this->set($i, 6, $v, $this::M_TIMING); // h
317
			$this->set(6, $i, $v, $this::M_TIMING); // v
318
		}
319
320
		return $this;
321
	}
322
323
	/**
324
	 * Draws the version information, 2x 3x6 pixel
325
	 *
326
	 * ISO/IEC 18004:2000 Section 8.10
327
	 */
328
	public function setVersionNumber(bool $test = null):QRMatrix{
329
		$bits = $this->version->getVersionPattern();
330
331
		if($bits !== null){
332
333
			for($i = 0; $i < 18; $i++){
334
				$a = (int)floor($i / 3);
335
				$b = $i % 3 + $this->moduleCount - 8 - 3;
336
				$v = !$test && (($bits >> $i) & 1) === 1;
0 ignored issues
show
Bug Best Practice introduced by
The expression $test of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
337
338
				$this->set($b, $a, $v, $this::M_VERSION); // ne
339
				$this->set($a, $b, $v, $this::M_VERSION); // sw
340
			}
341
342
		}
343
344
		return $this;
345
	}
346
347
	/**
348
	 * Draws the format info along the finder patterns
349
	 *
350
	 * ISO/IEC 18004:2000 Section 8.9
351
	 */
352
	public function setFormatInfo(int $maskPattern, bool $test = null):QRMatrix{
353
		$bits = $this->eccLevel->getformatPattern($maskPattern);
354
355
		for($i = 0; $i < 15; $i++){
356
			$v = !$test && (($bits >> $i) & 1) === 1;
0 ignored issues
show
Bug Best Practice introduced by
The expression $test of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
357
358
			if($i < 6){
359
				$this->set(8, $i, $v, $this::M_FORMAT);
360
			}
361
			elseif($i < 8){
362
				$this->set(8, $i + 1, $v, $this::M_FORMAT);
363
			}
364
			else{
365
				$this->set(8, $this->moduleCount - 15 + $i, $v, $this::M_FORMAT);
366
			}
367
368
			if($i < 8){
369
				$this->set($this->moduleCount - $i - 1, 8, $v, $this::M_FORMAT);
370
			}
371
			elseif($i < 9){
372
				$this->set(15 - $i, 8, $v, $this::M_FORMAT);
373
			}
374
			else{
375
				$this->set(15 - $i - 1, 8, $v, $this::M_FORMAT);
376
			}
377
378
		}
379
380
		$this->set(8, $this->moduleCount - 8, !$test, $this::M_FORMAT);
381
382
		return $this;
383
	}
384
385
	/**
386
	 * Draws the "quiet zone" of $size around the matrix
387
	 *
388
	 * ISO/IEC 18004:2000 Section 7.3.7
389
	 *
390
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
391
	 */
392
	public function setQuietZone(int $size = null):QRMatrix{
393
394
		if($this->matrix[$this->moduleCount - 1][$this->moduleCount - 1] === $this::M_NULL){
395
			throw new QRCodeDataException('use only after writing data');
396
		}
397
398
		$size = $size !== null
399
			? max(0, min($size, floor($this->moduleCount / 2)))
400
			: 4;
401
402
		for($y = 0; $y < $this->moduleCount; $y++){
403
			for($i = 0; $i < $size; $i++){
404
				array_unshift($this->matrix[$y], $this::M_QUIETZONE);
405
				array_push($this->matrix[$y], $this::M_QUIETZONE);
406
			}
407
		}
408
409
		$this->moduleCount += ($size * 2);
410
411
		$r = array_fill(0, $this->moduleCount, $this::M_QUIETZONE);
412
413
		for($i = 0; $i < $size; $i++){
414
			array_unshift($this->matrix, $r);
415
			array_push($this->matrix, $r);
416
		}
417
418
		return $this;
419
	}
420
421
	/**
422
	 * Clears a space of $width * $height in order to add a logo or text.
423
	 *
424
	 * Additionally, the logo space can be positioned within the QR Code - respecting the main functional patterns -
425
	 * using $startX and $startY. If either of these are null, the logo space will be centered in that direction.
426
	 * ECC level "H" (30%) is required.
427
	 *
428
	 * Please note that adding a logo space minimizes the error correction capacity of the QR Code and
429
	 * created images may become unreadable, especially when printed with a chance to receive damage.
430
	 * Please test thoroughly before using this feature in production.
431
	 *
432
	 * This method should be called from within an output module (after the matrix has been filled with data).
433
	 * Note that there is no restiction on how many times this method could be called on the same matrix instance.
434
	 *
435
	 * @link https://github.com/chillerlan/php-qrcode/issues/52
436
	 *
437
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
438
	 */
439
	public function setLogoSpace(int $width, int $height, int $startX = null, int $startY = null):QRMatrix{
440
441
		// for logos we operate in ECC H (30%) only
442
		if($this->eccLevel->getLevel() !== EccLevel::H){
443
			throw new QRCodeDataException('ECC level "H" required to add logo space');
444
		}
445
446
		// we need uneven sizes, adjust if needed
447
		if(($width % 2) === 0){
448
			$width++;
449
		}
450
451
		if(($height % 2) === 0){
452
			$height++;
453
		}
454
455
		// $this->moduleCount includes the quiet zone (if created), we need the QR size here
456
		$length = $this->version->getDimension();
457
458
		// throw if the logo space exceeds the maximum error correction capacity
459
		if($width * $height > floor($length * $length * 0.2)){
460
			throw new QRCodeDataException('logo space exceeds the maximum error correction capacity');
461
		}
462
463
		// quiet zone size
464
		$qz    = ($this->moduleCount - $length) / 2;
465
		// skip quiet zone and the first 9 rows/columns (finder-, mode-, version- and timing patterns)
466
		$start = $qz + 9;
467
		// skip quiet zone
468
		$end   = $this->moduleCount - $qz;
469
470
		// determine start coordinates
471
		$startX = ($startX !== null ? $startX : ($length - $width) / 2) + $qz;
472
		$startY = ($startY !== null ? $startY : ($length - $height) / 2) + $qz;
473
474
		// clear the space
475
		foreach($this->matrix as $y => $row){
476
			foreach($row as $x => $val){
477
				// out of bounds, skip
478
				if($x < $start || $y < $start ||$x >= $end || $y >= $end){
479
					continue;
480
				}
481
				// a match
482
				if($x >= $startX && $x < ($startX + $width) && $y >= $startY && $y < ($startY + $height)){
483
					$this->set($x, $y, false, $this::M_LOGO);
484
				}
485
			}
486
		}
487
488
		return $this;
489
	}
490
491
	/**
492
	 * Maps the binary $data array from QRData::maskECC() on the matrix,
493
	 * masking the data using $maskPattern (ISO/IEC 18004:2000 Section 8.8)
494
	 *
495
	 * @see \chillerlan\QRCode\Data\QRData::maskECC()
496
	 *
497
	 * @param \SplFixedArray<int> $data
498
	 * @param int                $maskPattern
499
	 *
500
	 * @return \chillerlan\QRCode\Data\QRMatrix
501
	 */
502
	public function mapData(SplFixedArray $data, int $maskPattern):QRMatrix{
503
		$this->maskPattern = $maskPattern;
504
		$byteCount         = $data->count();
505
		$y                 = $this->moduleCount - 1;
506
		$inc               = -1;
507
		$byteIndex         = 0;
508
		$bitIndex          = 7;
509
		$mask              = $this->getMask($this->maskPattern);
510
511
		for($i = $y; $i > 0; $i -= 2){
512
513
			if($i === 6){
514
				$i--;
515
			}
516
517
			while(true){
518
				for($c = 0; $c < 2; $c++){
519
					$x = $i - $c;
520
521
					if($this->matrix[$y][$x] === $this::M_NULL){
522
						$v = false;
523
524
						if($byteIndex < $byteCount){
525
							$v = (($data[$byteIndex] >> $bitIndex) & 1) === 1;
526
						}
527
528
						if($mask($x, $y) === 0){
529
							$v = !$v;
530
						}
531
532
						$this->matrix[$y][$x] = $this::M_DATA << ($v ? 8 : 0);
533
						$bitIndex--;
534
535
						if($bitIndex === -1){
536
							$byteIndex++;
537
							$bitIndex = 7;
538
						}
539
540
					}
541
				}
542
543
				$y += $inc;
544
545
				if($y < 0 || $this->moduleCount <= $y){
546
					$y   -=  $inc;
547
					$inc  = -$inc;
548
549
					break;
550
				}
551
552
			}
553
		}
554
555
		return $this;
556
	}
557
558
	/**
559
	 * ISO/IEC 18004:2000 Section 8.8.1
560
	 *
561
	 * Note that some versions of the QR code standard have had errors in the section about mask patterns.
562
	 * The information below has been corrected. (https://www.thonky.com/qr-code-tutorial/mask-patterns)
563
	 *
564
	 * @see \chillerlan\QRCode\QRMatrix::mapData()
565
	 *
566
	 * @internal
567
	 *
568
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
569
	 */
570
	protected function getMask(int $maskPattern):Closure{
571
572
		if((0b111 & $maskPattern) !== $maskPattern){
573
			throw new QRCodeDataException('invalid mask pattern'); // @codeCoverageIgnore
574
		}
575
576
		return [
577
			0b000 => fn($x, $y):int => ($x + $y) % 2,
578
			0b001 => fn($x, $y):int => $y % 2,
579
			0b010 => fn($x, $y):int => $x % 3,
0 ignored issues
show
Unused Code introduced by
The parameter $y is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

579
			0b010 => fn($x, /** @scrutinizer ignore-unused */ $y):int => $x % 3,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
580
			0b011 => fn($x, $y):int => ($x + $y) % 3,
581
			0b100 => fn($x, $y):int => ((int)($y / 2) + (int)($x / 3)) % 2,
582
			0b101 => fn($x, $y):int => (($x * $y) % 2) + (($x * $y) % 3),
583
			0b110 => fn($x, $y):int => ((($x * $y) % 2) + (($x * $y) % 3)) % 2,
584
			0b111 => fn($x, $y):int => ((($x * $y) % 3) + (($x + $y) % 2)) % 2,
585
		][$maskPattern];
586
	}
587
588
}
589