Passed
Push — v5 ( 902486...182ebf )
by smiley
02:36
created

QRMatrix   F

Complexity

Total Complexity 97

Size/Duplication

Total Lines 557
Duplicated Lines 0 %

Importance

Changes 13
Bugs 0 Features 0
Metric Value
eloc 187
dl 0
loc 557
rs 2
c 13
b 0
f 0
wmc 97

23 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 9 1
A set() 0 4 2
A matrix() 0 17 4
A version() 0 2 1
A __construct() 0 5 1
A get() 0 2 1
A size() 0 2 1
A maskPattern() 0 2 1
A eccLevel() 0 2 1
A setSeparators() 0 22 3
B setFormatInfo() 0 31 7
A setDarkModule() 0 4 1
A setVersionNumber() 0 17 4
A check() 0 2 1
A mask() 0 13 5
A flip() 0 4 1
A setQuietZone() 0 27 6
B mapData() 0 48 11
C setLogoSpace() 0 50 17
C setFinderPattern() 0 28 12
B setAlignmentPattern() 0 23 11
A setTimingPattern() 0 15 4
A checkType() 0 2 1

How to fix   Complexity   

Complex Class

Complex classes like QRMatrix often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use QRMatrix, and based on these observations, apply Extract Interface, too.

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