Passed
Push — master ( 514bca...891b04 )
by smiley
02:57
created

QRMatrix::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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