Debian Codegraph @

vendor/chillerlan/php-qrcode/src/Decoder/Decoder.php

raw
1 <?php
2 /**
3 * Class Decoder
4 *
5 * @created 17.01.2021
6 * @author ZXing Authors
7 * @author Smiley <[email protected]>
8 * @copyright 2021 Smiley
9 * @license Apache-2.0
10 */
11 declare(strict_types=1);
12
13 namespace chillerlan\QRCode\Decoder;
14
15 use chillerlan\QRCode\QROptions;
16 use chillerlan\QRCode\Common\{BitBuffer, EccLevel, LuminanceSourceInterface, MaskPattern, Mode, Version};
17 use chillerlan\QRCode\Data\{AlphaNum, Byte, ECI, Hanzi, Kanji, Number};
18 use chillerlan\QRCode\Detector\Detector;
19 use chillerlan\Settings\SettingsContainerInterface;
20 use Throwable;
21 use function chr, is_iterable, str_replace;
22
23 /**
24 * The main class which implements QR Code decoding -- as opposed to locating and extracting
25 * the QR Code from an image.
26 *
27 * @author Sean Owen
28 */
29 final class Decoder{
30
31 /** @noinspection PhpPropertyOnlyWrittenInspection (currently unused) */
32 private SettingsContainerInterface|QROptions $options;
33 private Version|null $version = null;
34 private EccLevel|null $eccLevel = null;
35 private MaskPattern|null $maskPattern = null;
36 private BitBuffer $bitBuffer;
37 private Detector $detector;
38
39 public function __construct(SettingsContainerInterface|QROptions|iterable $options = new QROptions){
40
41 if(is_iterable($options)){
42 $options = new QROptions($options);
43 }
44
45 $this->options = $options;
46 }
47
48 /**
49 * Decodes a QR Code represented as a BitMatrix.
50 * A 1 or "true" is taken to mean a black module.
51 *
52 * @throws \Throwable|\chillerlan\QRCode\Decoder\QRCodeDecoderException
53 */
54 public function decode(LuminanceSourceInterface $source):DecoderResult{
55 $this->detector = new Detector($source);
56 $matrix = $this->detector->detect();
57
58 try{
59 // clone the BitMatrix to avoid errors in case we run into mirroring
60 return $this->decodeMatrix(clone $matrix);
61 }
62 catch(Throwable $e){
63
64 try{
65 /*
66 * Prepare for a mirrored reading.
67 *
68 * Since we're here, this means we have successfully detected some kind
69 * of version and format information when mirrored. This is a good sign,
70 * that the QR code may be mirrored, and we should try once more with a
71 * mirrored content.
72 */
73 return $this->decodeMatrix($matrix->resetVersionInfo()->mirrorDiagonal());
74 }
75 catch(Throwable){
76 // Throw the exception from the original reading
77 throw $e;
78 }
79
80 }
81
82 }
83
84 /**
85 * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
86 */
87 private function decodeMatrix(BitMatrix $matrix):DecoderResult{
88 // Read raw codewords
89 $rawCodewords = $matrix->readCodewords();
90 $this->version = $matrix->getVersion();
91 $this->eccLevel = $matrix->getEccLevel();
92 $this->maskPattern = $matrix->getMaskPattern();
93
94 if($this->version === null || $this->eccLevel === null || $this->maskPattern === null){
95 throw new QRCodeDecoderException('unable to read version or format info'); // @codeCoverageIgnore
96 }
97
98 $resultBytes = (new ReedSolomonDecoder($this->version, $this->eccLevel))->decode($rawCodewords);
99
100 return $this->decodeBitStream($resultBytes);
101 }
102
103 /**
104 * Decode the contents of that stream of bytes
105 *
106 * @throws \chillerlan\QRCode\Decoder\QRCodeDecoderException
107 */
108 private function decodeBitStream(BitBuffer $bitBuffer):DecoderResult{
109 $this->bitBuffer = $bitBuffer;
110 $versionNumber = $this->version->getVersionNumber();
111 $symbolSequence = -1;
112 $parityData = -1;
113 $fc1InEffect = false;
114 $result = '';
115
116 // While still another segment to read...
117 while($this->bitBuffer->available() >= 4){
118 $datamode = $this->bitBuffer->read(4); // mode is encoded by 4 bits
119
120 // OK, assume we're done
121 if($datamode === Mode::TERMINATOR){
122 break;
123 }
124 elseif($datamode === Mode::NUMBER){
125 $result .= (new Number)->decodeSegment($this->bitBuffer, $versionNumber);
126 }
127 elseif($datamode === Mode::ALPHANUM){
128 $result .= $this->decodeAlphanumSegment($versionNumber, $fc1InEffect);
129 }
130 elseif($datamode === Mode::BYTE){
131 $result .= (new Byte)->decodeSegment($this->bitBuffer, $versionNumber);
132 }
133 elseif($datamode === Mode::KANJI){
134 $result .= (new Kanji)->decodeSegment($this->bitBuffer, $versionNumber);
135 }
136 elseif($datamode === Mode::STRCTURED_APPEND){
137
138 if($this->bitBuffer->available() < 16){
139 throw new QRCodeDecoderException('structured append: not enough bits left');
140 }
141 // sequence number and parity is added later to the result metadata
142 // Read next 8 bits (symbol sequence #) and 8 bits (parity data), then continue
143 $symbolSequence = $this->bitBuffer->read(8);
144 $parityData = $this->bitBuffer->read(8);
145 }
146 elseif($datamode === Mode::FNC1_FIRST || $datamode === Mode::FNC1_SECOND){
147 // We do little with FNC1 except alter the parsed result a bit according to the spec
148 $fc1InEffect = true;
149 }
150 elseif($datamode === Mode::ECI){
151 $result .= (new ECI)->decodeSegment($this->bitBuffer, $versionNumber);
152 }
153 elseif($datamode === Mode::HANZI){
154 $result .= (new Hanzi)->decodeSegment($this->bitBuffer, $versionNumber);
155 }
156 else{
157 throw new QRCodeDecoderException('invalid data mode');
158 }
159
160 }
161
162 return new DecoderResult([
163 'data' => $result,
164 'eccLevel' => $this->eccLevel,
165 'finderPatterns' => $this->detector->getFinderPatterns(),
166 'maskPattern' => $this->maskPattern,
167 'rawBytes' => $this->bitBuffer,
168 'structuredAppendParity' => $parityData,
169 'structuredAppendSequence' => $symbolSequence,
170 'version' => $this->version,
171 ]);
172 }
173
174 private function decodeAlphanumSegment(int $versionNumber, bool $fc1InEffect):string{
175 $str = (new AlphaNum)->decodeSegment($this->bitBuffer, $versionNumber);
176
177 // See section 6.4.8.1, 6.4.8.2
178 if($fc1InEffect){ // ???
179 // We need to massage the result a bit if in an FNC1 mode:
180 $str = str_replace(chr(0x1d), '%', $str);
181 $str = str_replace('%%', '%', $str);
182 }
183
184 return $str;
185 }
186
187 }