-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathEncoder.php
More file actions
480 lines (388 loc) · 14.9 KB
/
Copy pathEncoder.php
File metadata and controls
480 lines (388 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
<?php
declare(strict_types=1);
namespace GlobusStudio\QRCode\Encoder;
use GlobusStudio\QRCode\Data\AbstractQRData;
use GlobusStudio\QRCode\Data\AlphanumericData;
use GlobusStudio\QRCode\Data\ByteData;
use GlobusStudio\QRCode\Data\KanjiData;
use GlobusStudio\QRCode\Data\NumericData;
use GlobusStudio\QRCode\Data\QRDataInterface;
use GlobusStudio\QRCode\ErrorCorrection\ErrorCorrectionLevel;
use GlobusStudio\QRCode\ErrorCorrection\Polynomial;
use GlobusStudio\QRCode\ErrorCorrection\RSBlock;
use GlobusStudio\QRCode\Math\GaloisField;
use GlobusStudio\QRCode\Util\ModeDetector;
use GlobusStudio\QRCode\Util\Version;
final class Encoder
{
private const PAD0 = 0xEC;
private const PAD1 = 0x11;
private const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
private const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
private const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
/**
* @return bool[][]
*/
public static function encode(string $data, int $errorCorrectionLevel = ErrorCorrectionLevel::M, ?int $version = null, ?int $maskPattern = null): array
{
ErrorCorrectionLevel::validate($errorCorrectionLevel);
if ($maskPattern !== null && ($maskPattern < 0 || $maskPattern > 7)) {
throw new \InvalidArgumentException("Invalid mask pattern: $maskPattern (must be 0-7)");
}
$mode = ModeDetector::detect($data);
$qrData = self::createDataObject($data, $mode);
if ($version === null) {
$version = Version::getMinimumVersion(
$qrData->getLength(),
$mode,
$errorCorrectionLevel
);
}
$moduleCount = $version * 4 + 17;
$modules = self::createNullMatrix($moduleCount);
self::setupPositionProbePattern($modules, $moduleCount, 0, 0);
self::setupPositionProbePattern($modules, $moduleCount, $moduleCount - 7, 0);
self::setupPositionProbePattern($modules, $moduleCount, 0, $moduleCount - 7);
self::setupPositionAdjustPattern($modules, $moduleCount, $version);
self::setupTimingPattern($modules, $moduleCount);
$bestPattern = $maskPattern ?? self::findBestMaskPattern($modules, $moduleCount, $version, $errorCorrectionLevel, [$qrData]);
self::setupTypeInfo($modules, $moduleCount, false, $bestPattern, $errorCorrectionLevel);
if ($version >= 7) {
self::setupTypeNumber($modules, $moduleCount, false, $version);
}
$encodedData = self::createEncodedData($version, $errorCorrectionLevel, [$qrData]);
self::mapData($modules, $moduleCount, $encodedData, $bestPattern);
return self::toBoolMatrix($modules, $moduleCount);
}
private static function createDataObject(string $data, int $mode): QRDataInterface
{
switch ($mode) {
case AbstractQRData::MODE_NUMBER:
return new NumericData($data);
case AbstractQRData::MODE_ALPHA_NUM:
return new AlphanumericData($data);
case AbstractQRData::MODE_KANJI:
return new KanjiData($data);
default:
return new ByteData($data);
}
}
/**
* @return array<int, array<int, bool|null>>
*/
private static function createNullMatrix(int $size): array
{
$matrix = [];
for ($i = 0; $i < $size; $i++) {
$matrix[$i] = array_fill(0, $size, null);
}
return $matrix;
}
/**
* @param array<int, array<int, bool|null>> $modules
*/
private static function setupPositionProbePattern(array &$modules, int $moduleCount, int $row, int $col): void
{
for ($r = -1; $r <= 7; $r++) {
for ($c = -1; $c <= 7; $c++) {
if ($row + $r <= -1 || $moduleCount <= $row + $r
|| $col + $c <= -1 || $moduleCount <= $col + $c) {
continue;
}
$modules[$row + $r][$col + $c] =
(0 <= $r && $r <= 6 && ($c === 0 || $c === 6))
|| (0 <= $c && $c <= 6 && ($r === 0 || $r === 6))
|| (2 <= $r && $r <= 4 && 2 <= $c && $c <= 4);
}
}
}
/**
* @param array<int, array<int, bool|null>> $modules
*/
private static function setupPositionAdjustPattern(array &$modules, int $moduleCount, int $version): void
{
$pos = Version::getPatternPosition($version);
$posCount = count($pos);
for ($i = 0; $i < $posCount; $i++) {
for ($j = 0; $j < $posCount; $j++) {
$row = $pos[$i];
$col = $pos[$j];
if ($modules[$row][$col] !== null) {
continue;
}
for ($r = -2; $r <= 2; $r++) {
for ($c = -2; $c <= 2; $c++) {
$modules[$row + $r][$col + $c] =
$r === -2 || $r === 2 || $c === -2 || $c === 2 || ($r === 0 && $c === 0);
}
}
}
}
}
/**
* @param array<int, array<int, bool|null>> $modules
*/
private static function setupTimingPattern(array &$modules, int $moduleCount): void
{
for ($i = 8; $i < $moduleCount - 8; $i++) {
if ($modules[$i][6] !== null) {
continue;
}
$modules[$i][6] = ($i % 2 === 0);
$modules[6][$i] = ($i % 2 === 0);
}
}
/**
* @param array<int, array<int, bool|null>> $modules
*/
private static function setupTypeInfo(array &$modules, int $moduleCount, bool $test, int $maskPattern, int $errorCorrectionLevel): void
{
$data = ($errorCorrectionLevel << 3) | $maskPattern;
$bits = self::getBCHTypeInfo($data);
for ($i = 0; $i < 15; $i++) {
$mod = (!$test && (($bits >> $i) & 1) === 1);
if ($i < 6) {
$modules[$i][8] = $mod;
} elseif ($i < 8) {
$modules[$i + 1][8] = $mod;
} else {
$modules[$moduleCount - 15 + $i][8] = $mod;
}
if ($i < 8) {
$modules[8][$moduleCount - $i - 1] = $mod;
} elseif ($i < 9) {
$modules[8][15 - $i - 1 + 1] = $mod;
} else {
$modules[8][15 - $i - 1] = $mod;
}
}
$modules[$moduleCount - 8][8] = !$test;
}
/**
* @param array<int, array<int, bool|null>> $modules
*/
private static function setupTypeNumber(array &$modules, int $moduleCount, bool $test, int $version): void
{
$bits = self::getBCHTypeNumber($version);
for ($i = 0; $i < 18; $i++) {
$mod = (!$test && (($bits >> $i) & 1) === 1);
$modules[(int) ($i / 3)][$i % 3 + $moduleCount - 8 - 3] = $mod;
$modules[$i % 3 + $moduleCount - 8 - 3][(int) ($i / 3)] = $mod;
}
}
/**
* @param array<int, array<int, bool|null>> $modules
* @param QRDataInterface[] $dataList
*/
private static function findBestMaskPattern(array &$modules, int $moduleCount, int $version, int $errorCorrectionLevel, array $dataList): int
{
$minLostPoint = PHP_INT_MAX;
$bestPattern = 0;
for ($pattern = 0; $pattern < 8; $pattern++) {
$testModules = $modules;
self::setupTypeInfo($testModules, $moduleCount, true, $pattern, $errorCorrectionLevel);
if ($version >= 7) {
self::setupTypeNumber($testModules, $moduleCount, true, $version);
}
$data = self::createEncodedData($version, $errorCorrectionLevel, $dataList);
self::mapData($testModules, $moduleCount, $data, $pattern);
/** @var array<int, array<int, bool>> $boolMatrix */
$boolMatrix = self::toBoolMatrix($testModules, $moduleCount);
$lostPoint = MaskPattern::getLostPoint($boolMatrix, $moduleCount);
if ($lostPoint < $minLostPoint) {
$minLostPoint = $lostPoint;
$bestPattern = $pattern;
}
}
return $bestPattern;
}
/**
* @param QRDataInterface[] $dataList
* @return int[]
*/
private static function createEncodedData(int $version, int $errorCorrectionLevel, array $dataList): array
{
$rsBlocks = RSBlock::getBlocks($version, $errorCorrectionLevel);
$buffer = new BitBuffer();
foreach ($dataList as $data) {
$buffer->put($data->getMode(), 4);
$buffer->put($data->getLength(), $data->getLengthInBits($version));
$data->write($buffer);
}
$totalDataCount = 0;
foreach ($rsBlocks as $block) {
$totalDataCount += $block->getDataCount();
}
if ($buffer->getLengthInBits() > $totalDataCount * 8) {
throw new \OverflowException(
"Code length overflow: {$buffer->getLengthInBits()} > " . ($totalDataCount * 8)
);
}
if ($buffer->getLengthInBits() + 4 <= $totalDataCount * 8) {
$buffer->put(0, 4);
}
while ($buffer->getLengthInBits() % 8 !== 0) {
$buffer->putBit(false);
}
while ($buffer->getLengthInBits() < $totalDataCount * 8) {
$buffer->put(self::PAD0, 8);
if ($buffer->getLengthInBits() >= $totalDataCount * 8) {
break;
}
$buffer->put(self::PAD1, 8);
}
return self::createBytes($buffer, $rsBlocks);
}
/**
* @param RSBlock[] $rsBlocks
* @return int[]
*/
private static function createBytes(BitBuffer $buffer, array $rsBlocks): array
{
$offset = 0;
$maxDcCount = 0;
$maxEcCount = 0;
$rsBlockCount = count($rsBlocks);
/** @var array<int, int[]> $dcdata */
$dcdata = [];
/** @var array<int, int[]> $ecdata */
$ecdata = [];
for ($r = 0; $r < $rsBlockCount; $r++) {
$dcCount = $rsBlocks[$r]->getDataCount();
$ecCount = $rsBlocks[$r]->getTotalCount() - $dcCount;
$maxDcCount = max($maxDcCount, $dcCount);
$maxEcCount = max($maxEcCount, $ecCount);
/** @var int[] $dcRow */
$dcRow = array_fill(0, $dcCount, 0);
$bdata = $buffer->getBuffer();
for ($i = 0; $i < $dcCount; $i++) {
$dcRow[$i] = 0xFF & $bdata[$i + $offset];
}
$dcdata[$r] = $dcRow;
$offset += $dcCount;
$rsPoly = self::getErrorCorrectPolynomial($ecCount);
$rawPoly = new Polynomial($dcdata[$r], $rsPoly->getLength() - 1);
$modPoly = $rawPoly->mod($rsPoly);
$ecDataCount = $rsPoly->getLength() - 1;
/** @var int[] $ecRow */
$ecRow = array_fill(0, $ecDataCount, 0);
for ($i = 0; $i < $ecDataCount; $i++) {
$modIndex = $i + $modPoly->getLength() - $ecDataCount;
$ecRow[$i] = ($modIndex >= 0) ? $modPoly->get($modIndex) : 0;
}
$ecdata[$r] = $ecRow;
}
$totalCodeCount = 0;
for ($i = 0; $i < $rsBlockCount; $i++) {
$totalCodeCount += $rsBlocks[$i]->getTotalCount();
}
/** @var int[] $data */
$data = array_fill(0, $totalCodeCount, 0);
$index = 0;
for ($i = 0; $i < $maxDcCount; $i++) {
for ($r = 0; $r < $rsBlockCount; $r++) {
if ($i < count($dcdata[$r])) {
$data[$index++] = $dcdata[$r][$i];
}
}
}
for ($i = 0; $i < $maxEcCount; $i++) {
for ($r = 0; $r < $rsBlockCount; $r++) {
if ($i < count($ecdata[$r])) {
$data[$index++] = $ecdata[$r][$i];
}
}
}
return $data;
}
private static function getErrorCorrectPolynomial(int $errorCorrectLength): Polynomial
{
$a = new Polynomial([1]);
for ($i = 0; $i < $errorCorrectLength; $i++) {
$a = $a->multiply(new Polynomial([1, GaloisField::exp($i)]));
}
return $a;
}
/**
* @param array<int, array<int, bool|null>> $modules
* @param int[] $data
*/
private static function mapData(array &$modules, int $moduleCount, array $data, int $maskPattern): void
{
$inc = -1;
$row = $moduleCount - 1;
$bitIndex = 7;
$byteIndex = 0;
$dataCount = count($data);
for ($col = $moduleCount - 1; $col > 0; $col -= 2) {
if ($col === 6) {
$col--;
}
while (true) {
for ($c = 0; $c < 2; $c++) {
if ($modules[$row][$col - $c] === null) {
$dark = false;
if ($byteIndex < $dataCount) {
$dark = (($data[$byteIndex] >> $bitIndex) & 1) === 1;
}
if (MaskPattern::getMask($maskPattern, $row, $col - $c)) {
$dark = !$dark;
}
$modules[$row][$col - $c] = $dark;
$bitIndex--;
if ($bitIndex === -1) {
$byteIndex++;
$bitIndex = 7;
}
}
}
$row += $inc;
if ($row < 0 || $moduleCount <= $row) {
$row -= $inc;
$inc = -$inc;
break;
}
}
}
}
/**
* @param array<int, array<int, bool|null>> $modules
* @return bool[][]
*/
private static function toBoolMatrix(array $modules, int $moduleCount): array
{
$result = [];
for ($r = 0; $r < $moduleCount; $r++) {
$result[$r] = [];
for ($c = 0; $c < $moduleCount; $c++) {
$result[$r][$c] = $modules[$r][$c] === true;
}
}
return $result;
}
private static function getBCHTypeInfo(int $data): int
{
$d = $data << 10;
while (self::getBCHDigit($d) - self::getBCHDigit(self::G15) >= 0) {
$d ^= (self::G15 << (self::getBCHDigit($d) - self::getBCHDigit(self::G15)));
}
return (($data << 10) | $d) ^ self::G15_MASK;
}
private static function getBCHTypeNumber(int $data): int
{
$d = $data << 12;
while (self::getBCHDigit($d) - self::getBCHDigit(self::G18) >= 0) {
$d ^= (self::G18 << (self::getBCHDigit($d) - self::getBCHDigit(self::G18)));
}
return ($data << 12) | $d;
}
private static function getBCHDigit(int $data): int
{
$digit = 0;
while ($data !== 0) {
$digit++;
$data >>= 1;
}
return $digit;
}
}