Passed
Pull Request — main (#138)
by
unknown
01:53
created

QRMatrix::checkTypeIn()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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

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

335
		/** @scrutinizer ignore-call */ 
336
  $alignmentPattern = $this->version->getAlignmentPattern();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
336
337
		foreach($alignmentPattern as $y){
338
			foreach($alignmentPattern as $x){
339
340
				// skip existing patterns
341
				if($this->matrix[$y][$x] !== $this::M_NULL){
342
					continue;
343
				}
344
345
				for($ry = -2; $ry <= 2; $ry++){
346
					for($rx = -2; $rx <= 2; $rx++){
347
						$v = ($ry === 0 && $rx === 0) || $ry === 2 || $ry === -2 || $rx === 2 || $rx === -2;
348
349
						$this->set($x + $rx, $y + $ry, $v, $this::M_ALIGNMENT);
350
					}
351
				}
352
353
			}
354
		}
355
356
		return $this;
357
	}
358
359
360
	/**
361
	 * Draws the timing pattern (h/v checkered line between the finder patterns)
362
	 *
363
	 * ISO/IEC 18004:2000 Section 7.3.4
364
	 */
365
	public function setTimingPattern():self{
366
367
		foreach(range(8, $this->moduleCount - 8 - 1) as $i){
368
369
			if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
370
				continue;
371
			}
372
373
			$v = $i % 2 === 0;
374
375
			$this->set($i, 6, $v, $this::M_TIMING); // h
376
			$this->set(6, $i, $v, $this::M_TIMING); // v
377
		}
378
379
		return $this;
380
	}
381
382
	/**
383
	 * Draws the version information, 2x 3x6 pixel
384
	 *
385
	 * ISO/IEC 18004:2000 Section 8.10
386
	 */
387
	public function setVersionNumber():self{
388
		$bits = $this->version->getVersionPattern();
389
390
		if($bits !== null){
391
392
			for($i = 0; $i < 18; $i++){
393
				$a = (int)($i / 3);
394
				$b = $i % 3 + $this->moduleCount - 8 - 3;
395
				$v = (($bits >> $i) & 1) === 1;
396
397
				$this->set($b, $a, $v, $this::M_VERSION); // ne
398
				$this->set($a, $b, $v, $this::M_VERSION); // sw
399
			}
400
401
		}
402
403
		return $this;
404
	}
405
406
	/**
407
	 * Draws the format info along the finder patterns
408
	 *
409
	 * ISO/IEC 18004:2000 Section 8.9
410
	 */
411
	public function setFormatInfo():self{
412
		$bits = $this->eccLevel->getformatPattern($this->maskPattern);
0 ignored issues
show
Bug introduced by
It seems like $this->maskPattern can also be of type null; however, parameter $maskPattern of chillerlan\QRCode\Common...vel::getformatPattern() does only seem to accept chillerlan\QRCode\Common\MaskPattern, maybe add an additional type check? ( Ignorable by Annotation )

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

412
		$bits = $this->eccLevel->getformatPattern(/** @scrutinizer ignore-type */ $this->maskPattern);
Loading history...
Bug introduced by
The method getformatPattern() does not exist on null. ( Ignorable by Annotation )

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

412
		/** @scrutinizer ignore-call */ 
413
  $bits = $this->eccLevel->getformatPattern($this->maskPattern);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
413
414
		for($i = 0; $i < 15; $i++){
415
			$v = (($bits >> $i) & 1) === 1;
416
417
			if($i < 6){
418
				$this->set(8, $i, $v, $this::M_FORMAT);
419
			}
420
			elseif($i < 8){
421
				$this->set(8, $i + 1, $v, $this::M_FORMAT);
422
			}
423
			else{
424
				$this->set(8, $this->moduleCount - 15 + $i, $v, $this::M_FORMAT);
425
			}
426
427
			if($i < 8){
428
				$this->set($this->moduleCount - $i - 1, 8, $v, $this::M_FORMAT);
429
			}
430
			elseif($i < 9){
431
				$this->set(15 - $i, 8, $v, $this::M_FORMAT);
432
			}
433
			else{
434
				$this->set(15 - $i - 1, 8, $v, $this::M_FORMAT);
435
			}
436
437
		}
438
439
		return $this;
440
	}
441
442
	/**
443
	 * Draws the "quiet zone" of $size around the matrix
444
	 *
445
	 * ISO/IEC 18004:2000 Section 7.3.7
446
	 *
447
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
448
	 */
449
	public function setQuietZone(int $size = null):self{
450
451
		if($this->matrix[$this->moduleCount - 1][$this->moduleCount - 1] === $this::M_NULL){
452
			throw new QRCodeDataException('use only after writing data');
453
		}
454
455
		$size = $size !== null
456
			? max(0, min($size, floor($this->moduleCount / 2)))
457
			: 4;
458
459
		for($y = 0; $y < $this->moduleCount; $y++){
460
			for($i = 0; $i < $size; $i++){
461
				array_unshift($this->matrix[$y], $this::M_QUIETZONE);
462
				$this->matrix[$y][] = $this::M_QUIETZONE;
463
			}
464
		}
465
466
		$this->moduleCount += ($size * 2);
467
468
		$r = array_fill(0, $this->moduleCount, $this::M_QUIETZONE);
469
470
		for($i = 0; $i < $size; $i++){
471
			array_unshift($this->matrix, $r);
472
			$this->matrix[] = $r;
473
		}
474
475
		return $this;
476
	}
477
478
	/**
479
	 * Clears a space of $width * $height in order to add a logo or text.
480
	 *
481
	 * Additionally, the logo space can be positioned within the QR Code - respecting the main functional patterns -
482
	 * using $startX and $startY. If either of these are null, the logo space will be centered in that direction.
483
	 * ECC level "H" (30%) is required.
484
	 *
485
	 * Please note that adding a logo space minimizes the error correction capacity of the QR Code and
486
	 * created images may become unreadable, especially when printed with a chance to receive damage.
487
	 * Please test thoroughly before using this feature in production.
488
	 *
489
	 * This method should be called from within an output module (after the matrix has been filled with data).
490
	 * Note that there is no restiction on how many times this method could be called on the same matrix instance.
491
	 *
492
	 * @link https://github.com/chillerlan/php-qrcode/issues/52
493
	 *
494
	 * @throws \chillerlan\QRCode\Data\QRCodeDataException
495
	 */
496
	public function setLogoSpace(int $width, int $height, int $startX = null, int $startY = null):self{
497
498
		// for logos we operate in ECC H (30%) only
499
		if($this->eccLevel->getLevel() !== EccLevel::H){
500
			throw new QRCodeDataException('ECC level "H" required to add logo space');
501
		}
502
503
		// if width and height happen to be exactly 0 (default value), just return - nothing to do
504
		if($width === 0 || $height === 0){
505
			return $this;
506
		}
507
508
		// $this->moduleCount includes the quiet zone (if created), we need the QR size here
509
		$length = $this->version->getDimension();
510
511
		// throw if the size is negative or exceeds the qrcode size
512
		if($width < 0 || $height < 0 || $width > $length || $height > $length){
513
			throw new QRCodeDataException('invalid logo dimensions');
514
		}
515
516
		// we need uneven sizes to center the logo space, adjust if needed
517
		if($startX === null && ($width % 2) === 0){
518
			$width++;
519
		}
520
521
		if($startY === null && ($height % 2) === 0){
522
			$height++;
523
		}
524
525
		// throw if the logo space exceeds the maximum error correction capacity
526
		if($width * $height > floor($length * $length * 0.2)){
527
			throw new QRCodeDataException('logo space exceeds the maximum error correction capacity');
528
		}
529
530
		// quiet zone size
531
		$qz    = ($this->moduleCount - $length) / 2;
532
		// skip quiet zone and the first 9 rows/columns (finder-, mode-, version- and timing patterns)
533
		$start = $qz + 9;
534
		// skip quiet zone
535
		$end   = $this->moduleCount - $qz;
536
537
		// determine start coordinates
538
		$startX = ($startX !== null ? $startX : ($length - $width) / 2) + $qz;
539
		$startY = ($startY !== null ? $startY : ($length - $height) / 2) + $qz;
540
541
		// clear the space
542
		foreach($this->matrix as $y => $row){
543
			foreach($row as $x => $val){
544
				// out of bounds, skip
545
				if($x < $start || $y < $start ||$x >= $end || $y >= $end){
546
					continue;
547
				}
548
				// a match
549
				if($x >= $startX && $x < ($startX + $width) && $y >= $startY && $y < ($startY + $height)){
550
					$this->set($x, $y, false, $this::M_LOGO);
551
				}
552
			}
553
		}
554
555
		return $this;
556
	}
557
558
	/**
559
	 * Maps the interleaved binary $data on the matrix
560
	 */
561
	public function writeCodewords(BitBuffer $bitBuffer):self{
562
		$data      = (new ReedSolomonEncoder)->interleaveEcBytes($bitBuffer, $this->version, $this->eccLevel);
0 ignored issues
show
Bug introduced by
It seems like $this->version can also be of type null; however, parameter $version of chillerlan\QRCode\Common...er::interleaveEcBytes() does only seem to accept chillerlan\QRCode\Common\Version, maybe add an additional type check? ( Ignorable by Annotation )

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

562
		$data      = (new ReedSolomonEncoder)->interleaveEcBytes($bitBuffer, /** @scrutinizer ignore-type */ $this->version, $this->eccLevel);
Loading history...
Bug introduced by
It seems like $this->eccLevel can also be of type null; however, parameter $eccLevel of chillerlan\QRCode\Common...er::interleaveEcBytes() does only seem to accept chillerlan\QRCode\Common\EccLevel, maybe add an additional type check? ( Ignorable by Annotation )

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

562
		$data      = (new ReedSolomonEncoder)->interleaveEcBytes($bitBuffer, $this->version, /** @scrutinizer ignore-type */ $this->eccLevel);
Loading history...
563
		$byteCount = count($data);
564
		$iByte     = 0;
565
		$iBit      = 7;
566
		$direction = true;
567
568
		for($i = $this->moduleCount - 1; $i > 0; $i -= 2){
569
570
			// skip vertical alignment pattern
571
			if($i === 6){
572
				$i--;
573
			}
574
575
			for($count = 0; $count < $this->moduleCount; $count++){
576
				$y = $direction ? $this->moduleCount - 1 - $count : $count;
577
578
				for($col = 0; $col < 2; $col++){
579
					$x = $i - $col;
580
581
					// skip functional patterns
582
					if($this->get($x, $y) !== $this::M_NULL){
583
						continue;
584
					}
585
586
					$v = $iByte < $byteCount && (($data[$iByte] >> $iBit--) & 1) === 1;
587
588
					$this->set($x, $y, $v, $this::M_DATA);
589
590
					if($iBit === -1){
591
						$iByte++;
592
						$iBit = 7;
593
					}
594
				}
595
			}
596
597
			$direction = !$direction; // switch directions
0 ignored issues
show
introduced by
The condition $direction is always true.
Loading history...
598
		}
599
600
		return $this;
601
	}
602
603
	/**
604
	 * Applies/reverses the mask pattern
605
	 *
606
	 * ISO/IEC 18004:2000 Section 8.8.1
607
	 */
608
	public function mask():self{
609
		$mask = $this->maskPattern->getMask();
0 ignored issues
show
Bug introduced by
The method getMask() does not exist on null. ( Ignorable by Annotation )

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

609
		/** @scrutinizer ignore-call */ 
610
  $mask = $this->maskPattern->getMask();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
610
611
		foreach($this->matrix as $y => $row){
612
			foreach($row as $x => $val){
613
				if($mask($x, $y) && ($val & $this::M_DATA) === $this::M_DATA){
614
					$this->flip($x, $y);
615
				}
616
			}
617
		}
618
619
		return $this;
620
	}
621
622
}
623