QRMatrix.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. <?php
  2. /**
  3. * Class QRMatrix
  4. *
  5. * @created 15.11.2017
  6. * @author Smiley <smiley@chillerlan.net>
  7. * @copyright 2017 Smiley
  8. * @license MIT
  9. */
  10. namespace chillerlan\QRCode\Data;
  11. use chillerlan\QRCode\Common\{EccLevel, MaskPattern, Version};
  12. use SplFixedArray;
  13. use function array_fill, array_push, array_unshift, floor, max, min, range;
  14. /**
  15. * Holds a numerical representation of the final QR Code;
  16. * maps the ECC coded binary data and applies the mask pattern
  17. *
  18. * @see http://www.thonky.com/qr-code-tutorial/format-version-information
  19. */
  20. final class QRMatrix{
  21. /** @var int */
  22. public const M_NULL = 0b000000000000;
  23. /** @var int */
  24. public const M_DARKMODULE = 0b000000000001;
  25. /** @var int */
  26. public const M_DATA = 0b000000000010;
  27. /** @var int */
  28. public const M_FINDER = 0b000000000100;
  29. /** @var int */
  30. public const M_SEPARATOR = 0b000000001000;
  31. /** @var int */
  32. public const M_ALIGNMENT = 0b000000010000;
  33. /** @var int */
  34. public const M_TIMING = 0b000000100000;
  35. /** @var int */
  36. public const M_FORMAT = 0b000001000000;
  37. /** @var int */
  38. public const M_VERSION = 0b000010000000;
  39. /** @var int */
  40. public const M_QUIETZONE = 0b000100000000;
  41. /** @var int */
  42. public const M_LOGO = 0b001000000000;
  43. /** @var int */
  44. public const M_FINDER_DOT = 0b010000000000;
  45. /** @var int */
  46. public const M_TEST = 0b011111111111;
  47. /** @var int */
  48. public const IS_DARK = 0b100000000000;
  49. /**
  50. * the used mask pattern, set via QRMatrix::mask()
  51. */
  52. private ?MaskPattern $maskPattern = null;
  53. /**
  54. * the size (side length) of the matrix, including quiet zone (if created)
  55. */
  56. private int $moduleCount;
  57. /**
  58. * the actual matrix data array
  59. *
  60. * @var int[][]
  61. */
  62. private array $matrix;
  63. /**
  64. * the current ECC level
  65. */
  66. private EccLevel $eccLevel;
  67. /**
  68. * a Version instance
  69. */
  70. private Version $version;
  71. /**
  72. * QRMatrix constructor.
  73. */
  74. public function __construct(Version $version, EccLevel $eccLevel){
  75. $this->version = $version;
  76. $this->eccLevel = $eccLevel;
  77. $this->moduleCount = $this->version->getDimension();
  78. $this->matrix = array_fill(0, $this->moduleCount, array_fill(0, $this->moduleCount, $this::M_NULL));
  79. }
  80. /**
  81. * shortcut to initialize the matrix
  82. */
  83. public function init(MaskPattern $maskPattern, bool $test = null):QRMatrix{
  84. return $this
  85. ->setFinderPattern()
  86. ->setSeparators()
  87. ->setAlignmentPattern()
  88. ->setTimingPattern()
  89. ->setVersionNumber($test)
  90. ->setFormatInfo($maskPattern, $test)
  91. ->setDarkModule()
  92. ;
  93. }
  94. /**
  95. * Returns the data matrix, returns a pure boolean representation if $boolean is set to true
  96. *
  97. * @return int[][]|bool[][]
  98. */
  99. public function matrix(bool $boolean = false):array{
  100. if(!$boolean){
  101. return $this->matrix;
  102. }
  103. $matrix = [];
  104. foreach($this->matrix as $y => $row){
  105. $matrix[$y] = [];
  106. foreach($row as $x => $val){
  107. $matrix[$y][$x] = ($val & $this::IS_DARK) === $this::IS_DARK;
  108. }
  109. }
  110. return $matrix;
  111. }
  112. /**
  113. * Returns the current version number
  114. */
  115. public function version():Version{
  116. return $this->version;
  117. }
  118. /**
  119. * Returns the current ECC level
  120. */
  121. public function eccLevel():EccLevel{
  122. return $this->eccLevel;
  123. }
  124. /**
  125. * Returns the current mask pattern
  126. */
  127. public function maskPattern():?MaskPattern{
  128. return $this->maskPattern;
  129. }
  130. /**
  131. * Returns the absoulute size of the matrix, including quiet zone (after setting it).
  132. *
  133. * size = version * 4 + 17 [ + 2 * quietzone size]
  134. */
  135. public function size():int{
  136. return $this->moduleCount;
  137. }
  138. /**
  139. * Returns the value of the module at position [$x, $y]
  140. */
  141. public function get(int $x, int $y):int{
  142. return $this->matrix[$y][$x];
  143. }
  144. /**
  145. * Sets the $M_TYPE value for the module at position [$x, $y]
  146. *
  147. * true => $M_TYPE | 0x800
  148. * false => $M_TYPE
  149. */
  150. public function set(int $x, int $y, bool $value, int $M_TYPE):QRMatrix{
  151. $this->matrix[$y][$x] = $M_TYPE | ($value ? $this::IS_DARK : 0);
  152. return $this;
  153. }
  154. /**
  155. * Flips the value of the module
  156. */
  157. public function flip(int $x, int $y):QRMatrix{
  158. $this->matrix[$y][$x] ^= $this::IS_DARK;
  159. return $this;
  160. }
  161. /**
  162. * Checks whether a module is of the given $M_TYPE
  163. *
  164. * true => $value & $M_TYPE === $M_TYPE
  165. */
  166. public function checkType(int $x, int $y, int $M_TYPE):bool{
  167. return ($this->matrix[$y][$x] & $M_TYPE) === $M_TYPE;
  168. }
  169. /**
  170. * Checks whether a module is true (dark) or false (light)
  171. *
  172. * true => $value & 0x800 === 0x800
  173. * false => $value & 0x800 === 0
  174. */
  175. public function check(int $x, int $y):bool{
  176. return $this->checkType($x, $y, $this::IS_DARK);
  177. }
  178. /**
  179. * Sets the "dark module", that is always on the same position 1x1px away from the bottom left finder
  180. */
  181. public function setDarkModule():QRMatrix{
  182. $this->set(8, 4 * $this->version->getVersionNumber() + 9, true, $this::M_DARKMODULE);
  183. return $this;
  184. }
  185. /**
  186. * Draws the 7x7 finder patterns in the corners top left/right and bottom left
  187. *
  188. * ISO/IEC 18004:2000 Section 7.3.2
  189. */
  190. public function setFinderPattern():QRMatrix{
  191. $pos = [
  192. [0, 0], // top left
  193. [$this->moduleCount - 7, 0], // bottom left
  194. [0, $this->moduleCount - 7], // top right
  195. ];
  196. foreach($pos as $c){
  197. for($y = 0; $y < 7; $y++){
  198. for($x = 0; $x < 7; $x++){
  199. // outer (dark) 7*7 square
  200. if($x === 0 || $x === 6 || $y === 0 || $y === 6){
  201. $this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER);
  202. }
  203. // inner (light) 5*5 square
  204. elseif($x === 1 || $x === 5 || $y === 1 || $y === 5){
  205. $this->set($c[0] + $y, $c[1] + $x, false, $this::M_FINDER);
  206. }
  207. // 3*3 dot
  208. else{
  209. $this->set($c[0] + $y, $c[1] + $x, true, $this::M_FINDER_DOT);
  210. }
  211. }
  212. }
  213. }
  214. return $this;
  215. }
  216. /**
  217. * Draws the separator lines around the finder patterns
  218. *
  219. * ISO/IEC 18004:2000 Section 7.3.3
  220. */
  221. public function setSeparators():QRMatrix{
  222. $h = [
  223. [7, 0],
  224. [$this->moduleCount - 8, 0],
  225. [7, $this->moduleCount - 8],
  226. ];
  227. $v = [
  228. [7, 7],
  229. [$this->moduleCount - 1, 7],
  230. [7, $this->moduleCount - 8],
  231. ];
  232. for($c = 0; $c < 3; $c++){
  233. for($i = 0; $i < 8; $i++){
  234. $this->set($h[$c][0] , $h[$c][1] + $i, false, $this::M_SEPARATOR);
  235. $this->set($v[$c][0] - $i, $v[$c][1] , false, $this::M_SEPARATOR);
  236. }
  237. }
  238. return $this;
  239. }
  240. /**
  241. * Draws the 5x5 alignment patterns
  242. *
  243. * ISO/IEC 18004:2000 Section 7.3.5
  244. */
  245. public function setAlignmentPattern():QRMatrix{
  246. $alignmentPattern = $this->version->getAlignmentPattern();
  247. foreach($alignmentPattern as $y){
  248. foreach($alignmentPattern as $x){
  249. // skip existing patterns
  250. if($this->matrix[$y][$x] !== $this::M_NULL){
  251. continue;
  252. }
  253. for($ry = -2; $ry <= 2; $ry++){
  254. for($rx = -2; $rx <= 2; $rx++){
  255. $v = ($ry === 0 && $rx === 0) || $ry === 2 || $ry === -2 || $rx === 2 || $rx === -2;
  256. $this->set($x + $rx, $y + $ry, $v, $this::M_ALIGNMENT);
  257. }
  258. }
  259. }
  260. }
  261. return $this;
  262. }
  263. /**
  264. * Draws the timing pattern (h/v checkered line between the finder patterns)
  265. *
  266. * ISO/IEC 18004:2000 Section 7.3.4
  267. */
  268. public function setTimingPattern():QRMatrix{
  269. foreach(range(8, $this->moduleCount - 8 - 1) as $i){
  270. if($this->matrix[6][$i] !== $this::M_NULL || $this->matrix[$i][6] !== $this::M_NULL){
  271. continue;
  272. }
  273. $v = $i % 2 === 0;
  274. $this->set($i, 6, $v, $this::M_TIMING); // h
  275. $this->set(6, $i, $v, $this::M_TIMING); // v
  276. }
  277. return $this;
  278. }
  279. /**
  280. * Draws the version information, 2x 3x6 pixel
  281. *
  282. * ISO/IEC 18004:2000 Section 8.10
  283. */
  284. public function setVersionNumber(bool $test = null):QRMatrix{
  285. $bits = $this->version->getVersionPattern();
  286. if($bits !== null){
  287. for($i = 0; $i < 18; $i++){
  288. $a = (int)($i / 3);
  289. $b = $i % 3 + $this->moduleCount - 8 - 3;
  290. $v = !$test && (($bits >> $i) & 1) === 1;
  291. $this->set($b, $a, $v, $this::M_VERSION); // ne
  292. $this->set($a, $b, $v, $this::M_VERSION); // sw
  293. }
  294. }
  295. return $this;
  296. }
  297. /**
  298. * Draws the format info along the finder patterns
  299. *
  300. * ISO/IEC 18004:2000 Section 8.9
  301. */
  302. public function setFormatInfo(MaskPattern $maskPattern, bool $test = null):QRMatrix{
  303. $bits = $this->eccLevel->getformatPattern($maskPattern);
  304. for($i = 0; $i < 15; $i++){
  305. $v = !$test && (($bits >> $i) & 1) === 1;
  306. if($i < 6){
  307. $this->set(8, $i, $v, $this::M_FORMAT);
  308. }
  309. elseif($i < 8){
  310. $this->set(8, $i + 1, $v, $this::M_FORMAT);
  311. }
  312. else{
  313. $this->set(8, $this->moduleCount - 15 + $i, $v, $this::M_FORMAT);
  314. }
  315. if($i < 8){
  316. $this->set($this->moduleCount - $i - 1, 8, $v, $this::M_FORMAT);
  317. }
  318. elseif($i < 9){
  319. $this->set(15 - $i, 8, $v, $this::M_FORMAT);
  320. }
  321. else{
  322. $this->set(15 - $i - 1, 8, $v, $this::M_FORMAT);
  323. }
  324. }
  325. $this->set(8, $this->moduleCount - 8, !$test, $this::M_FORMAT);
  326. return $this;
  327. }
  328. /**
  329. * Draws the "quiet zone" of $size around the matrix
  330. *
  331. * ISO/IEC 18004:2000 Section 7.3.7
  332. *
  333. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  334. */
  335. public function setQuietZone(int $size = null):QRMatrix{
  336. if($this->matrix[$this->moduleCount - 1][$this->moduleCount - 1] === $this::M_NULL){
  337. throw new QRCodeDataException('use only after writing data');
  338. }
  339. $size = $size !== null
  340. ? max(0, min($size, floor($this->moduleCount / 2)))
  341. : 4;
  342. for($y = 0; $y < $this->moduleCount; $y++){
  343. for($i = 0; $i < $size; $i++){
  344. array_unshift($this->matrix[$y], $this::M_QUIETZONE);
  345. array_push($this->matrix[$y], $this::M_QUIETZONE);
  346. }
  347. }
  348. $this->moduleCount += ($size * 2);
  349. $r = array_fill(0, $this->moduleCount, $this::M_QUIETZONE);
  350. for($i = 0; $i < $size; $i++){
  351. array_unshift($this->matrix, $r);
  352. array_push($this->matrix, $r);
  353. }
  354. return $this;
  355. }
  356. /**
  357. * Clears a space of $width * $height in order to add a logo or text.
  358. *
  359. * Additionally, the logo space can be positioned within the QR Code - respecting the main functional patterns -
  360. * using $startX and $startY. If either of these are null, the logo space will be centered in that direction.
  361. * ECC level "H" (30%) is required.
  362. *
  363. * Please note that adding a logo space minimizes the error correction capacity of the QR Code and
  364. * created images may become unreadable, especially when printed with a chance to receive damage.
  365. * Please test thoroughly before using this feature in production.
  366. *
  367. * This method should be called from within an output module (after the matrix has been filled with data).
  368. * Note that there is no restiction on how many times this method could be called on the same matrix instance.
  369. *
  370. * @link https://github.com/chillerlan/php-qrcode/issues/52
  371. *
  372. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  373. */
  374. public function setLogoSpace(int $width, int $height, int $startX = null, int $startY = null):QRMatrix{
  375. // for logos we operate in ECC H (30%) only
  376. if($this->eccLevel->getLevel() !== EccLevel::H){
  377. throw new QRCodeDataException('ECC level "H" required to add logo space');
  378. }
  379. // we need uneven sizes to center the logo space, adjust if needed
  380. if($startX === null && ($width % 2) === 0){
  381. $width++;
  382. }
  383. if($startY === null && ($height % 2) === 0){
  384. $height++;
  385. }
  386. // $this->moduleCount includes the quiet zone (if created), we need the QR size here
  387. $length = $this->version->getDimension();
  388. // throw if the logo space exceeds the maximum error correction capacity
  389. if($width * $height > floor($length * $length * 0.2)){
  390. throw new QRCodeDataException('logo space exceeds the maximum error correction capacity');
  391. }
  392. // quiet zone size
  393. $qz = ($this->moduleCount - $length) / 2;
  394. // skip quiet zone and the first 9 rows/columns (finder-, mode-, version- and timing patterns)
  395. $start = $qz + 9;
  396. // skip quiet zone
  397. $end = $this->moduleCount - $qz;
  398. // determine start coordinates
  399. $startX = ($startX !== null ? $startX : ($length - $width) / 2) + $qz;
  400. $startY = ($startY !== null ? $startY : ($length - $height) / 2) + $qz;
  401. // clear the space
  402. foreach($this->matrix as $y => $row){
  403. foreach($row as $x => $val){
  404. // out of bounds, skip
  405. if($x < $start || $y < $start ||$x >= $end || $y >= $end){
  406. continue;
  407. }
  408. // a match
  409. if($x >= $startX && $x < ($startX + $width) && $y >= $startY && $y < ($startY + $height)){
  410. $this->set($x, $y, false, $this::M_LOGO);
  411. }
  412. }
  413. }
  414. return $this;
  415. }
  416. /**
  417. * Maps the binary $data array from QRData::maskECC() on the matrix,
  418. * masking the data using $maskPattern (ISO/IEC 18004:2000 Section 8.8)
  419. *
  420. * @see \chillerlan\QRCode\Data\QRData::maskECC()
  421. *
  422. * @param \SplFixedArray<int> $data
  423. *
  424. * @return \chillerlan\QRCode\Data\QRMatrix
  425. */
  426. public function mapData(SplFixedArray $data):QRMatrix{
  427. $byteCount = $data->count();
  428. $y = $this->moduleCount - 1;
  429. $inc = -1;
  430. $byteIndex = 0;
  431. $bitIndex = 7;
  432. for($i = $y; $i > 0; $i -= 2){
  433. if($i === 6){
  434. $i--;
  435. }
  436. while(true){
  437. for($c = 0; $c < 2; $c++){
  438. $x = $i - $c;
  439. if($this->matrix[$y][$x] === $this::M_NULL){
  440. $v = false;
  441. if($byteIndex < $byteCount){
  442. $v = (($data[$byteIndex] >> $bitIndex) & 1) === 1;
  443. }
  444. $this->matrix[$y][$x] = $this::M_DATA | ($v ? $this::IS_DARK : 0);
  445. $bitIndex--;
  446. if($bitIndex === -1){
  447. $byteIndex++;
  448. $bitIndex = 7;
  449. }
  450. }
  451. }
  452. $y += $inc;
  453. if($y < 0 || $this->moduleCount <= $y){
  454. $y -= $inc;
  455. $inc = -$inc;
  456. break;
  457. }
  458. }
  459. }
  460. return $this;
  461. }
  462. /**
  463. * Applies the mask pattern
  464. *
  465. * ISO/IEC 18004:2000 Section 8.8.1
  466. */
  467. public function mask(MaskPattern $maskPattern):QRMatrix{
  468. $this->maskPattern = $maskPattern;
  469. $mask = $this->maskPattern->getMask();
  470. foreach($this->matrix as $y => &$row){
  471. foreach($row as $x => &$val){
  472. if($mask($x, $y) === 0 && ($val & $this::M_DATA) === $this::M_DATA){
  473. $val ^= $this::IS_DARK;
  474. }
  475. }
  476. }
  477. return $this;
  478. }
  479. }