Debian Codegraph @

vendor/chillerlan/php-qrcode/src/Output/QROutputAbstract.php

raw
1 <?php
2 /**
3 * Class QROutputAbstract
4 *
5 * @created 09.12.2015
6 * @author Smiley <[email protected]>
7 * @copyright 2015 Smiley
8 * @license MIT
9 *
10 * @noinspection PhpComposerExtensionStubsInspection
11 */
12 declare(strict_types=1);
13
14 namespace chillerlan\QRCode\Output;
15
16 use chillerlan\QRCode\QROptions;
17 use chillerlan\QRCode\Data\QRMatrix;
18 use chillerlan\Settings\SettingsContainerInterface;
19 use finfo;
20 use function base64_encode, dirname, extension_loaded, file_put_contents, is_iterable, is_writable, ksort, sprintf;
21 use const FILEINFO_MIME_TYPE;
22
23 /**
24 * common output abstract
25 */
26 abstract class QROutputAbstract implements QROutputInterface{
27
28 /**
29 * the current size of the QR matrix
30 *
31 * @see \chillerlan\QRCode\Data\QRMatrix::getSize()
32 */
33 protected int $moduleCount;
34
35 /**
36 * the side length of the QR image (modules * scale)
37 */
38 protected int $length;
39
40 /**
41 * The current module scale value (might have been modified)
42 *
43 * @see \chillerlan\QRCode\QROptions::$scale
44 */
45 protected int $scale;
46
47 /**
48 * an (optional) array of color values for the several QR matrix parts
49 *
50 * @phpstan-var array<int, mixed>
51 */
52 protected array $moduleValues;
53
54 /**
55 * the (filled) data matrix object
56 */
57 protected QRMatrix $matrix;
58
59 /**
60 * the options instance
61 */
62 protected SettingsContainerInterface|QROptions $options;
63
64 /**
65 * @see \chillerlan\QRCode\QROptions::$excludeFromConnect
66 * @var int[]
67 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->excludeFromConnect` instead.
68 */
69 protected array $excludeFromConnect;
70
71 /**
72 * @see \chillerlan\QRCode\QROptions::$keepAsSquare
73 * @var int[]
74 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->keepAsSquare` instead.
75 */
76 protected array $keepAsSquare;
77
78 /**
79 * @see \chillerlan\QRCode\QROptions::$connectPaths
80 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->connectPaths` instead.
81 */
82 protected bool $connectPaths;
83
84 /**
85 * @see \chillerlan\QRCode\QROptions::$eol
86 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->eol` instead.
87 */
88 protected string $eol;
89
90 /**
91 * @see \chillerlan\QRCode\QROptions::$drawLightModules
92 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->drawLightModules` instead.
93 */
94 protected bool $drawLightModules;
95
96 /**
97 * @see \chillerlan\QRCode\QROptions::$drawCircularModules
98 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->drawCircularModules` instead.
99 */
100 protected bool $drawCircularModules;
101
102 /**
103 * @see \chillerlan\QRCode\QROptions::$circleRadius
104 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->circleRadius` instead.
105 */
106 protected float $circleRadius;
107
108 /**
109 * @deprecated 6.0.1 This property will be removed in v7, use `$this->options->circleRadius * 2` instead.
110 */
111 protected float $circleDiameter;
112
113 /**
114 * QROutputAbstract constructor.
115 */
116 public function __construct(SettingsContainerInterface|QROptions|iterable $options, QRMatrix $matrix){
117
118 if(is_iterable($options)){
119 $options = new QROptions($options);
120 }
121
122 $this->options = $options;
123 $this->matrix = $matrix;
124
125 if($this->options->invertMatrix){
126 $this->matrix->invert();
127 }
128
129 $this->copyVars();
130 $this->setMatrixDimensions();
131 $this->setModuleValues();
132 }
133
134 /**
135 * Creates copies of several QROptions values to avoid calling the magic getters/property hooks
136 * in long loops for a significant performance increase.
137 *
138 * These variables are usually used in the "module" methods and are called up to 31329 times (at version 40).
139 *
140 * @deprecated 6.0.1 This method will be removed in v7 without replacement (unnecessary).
141 */
142 protected function copyVars():void{
143
144 $vars = [
145 'connectPaths',
146 'excludeFromConnect',
147 'eol',
148 'drawLightModules',
149 'drawCircularModules',
150 'keepAsSquare',
151 'circleRadius',
152 ];
153
154 foreach($vars as $property){
155 $this->{$property} = $this->options->{$property};
156 }
157
158 $this->circleDiameter = ($this->circleRadius * 2);
159 }
160
161 /**
162 * Sets/updates the matrix dimensions
163 *
164 * Call this method if you modify the matrix from within your custom output class in case the dimensions have been changed
165 */
166 protected function setMatrixDimensions():void{
167 $this->moduleCount = $this->matrix->getSize();
168 $this->scale = $this->options->scale;
169 $this->length = ($this->moduleCount * $this->scale);
170 }
171
172 /**
173 * Returns a 2 element array with the current output width and height
174 *
175 * The type and units of the values depend on the output class. The default value is the current module count * scale.
176 *
177 * @return int[]
178 */
179 protected function getOutputDimensions():array{
180 return [$this->length, $this->length];
181 }
182
183 /**
184 * Sets the initial module values
185 */
186 protected function setModuleValues():void{
187
188 // first fill the map with the default values
189 foreach($this::DEFAULT_MODULE_VALUES as $M_TYPE => $defaultValue){
190 $this->moduleValues[$M_TYPE] = $this->getDefaultModuleValue($defaultValue);
191 }
192
193 // now loop over the options values to replace defaults and add extra values
194 /** @var int $M_TYPE */
195 foreach($this->options->moduleValues as $M_TYPE => $value){
196 if($this::moduleValueIsValid($value)){
197 $this->moduleValues[$M_TYPE] = $this->prepareModuleValue($value);
198 }
199 }
200
201 }
202
203 /**
204 * Prepares the value for the given input (return value depends on the output class)
205 */
206 abstract protected function prepareModuleValue(mixed $value):mixed;
207
208 /**
209 * Returns a default value for either dark or light modules (return value depends on the output class)
210 */
211 abstract protected function getDefaultModuleValue(bool $isDark):mixed;
212
213 /**
214 * Returns the prepared value for the given $M_TYPE
215 *
216 * @throws \chillerlan\QRCode\Output\QRCodeOutputException if $moduleValues[$M_TYPE] doesn't exist
217 */
218 protected function getModuleValue(int $M_TYPE):mixed{
219
220 if(!isset($this->moduleValues[$M_TYPE])){
221 throw new QRCodeOutputException(sprintf('$M_TYPE %012b not found in module values map', $M_TYPE));
222 }
223
224 return $this->moduleValues[$M_TYPE];
225 }
226
227 /**
228 * Returns the prepared module value at the given coordinate [$x, $y] (convenience)
229 */
230 protected function getModuleValueAt(int $x, int $y):mixed{
231 return $this->getModuleValue($this->matrix->get($x, $y));
232 }
233
234 /**
235 * Returns a base64 data URI for the given string and mime type
236 *
237 * The mime type can be set via class constant MIME_TYPE in child classes,
238 * or given via $mime, otherwise it is guessed from the image $data.
239 */
240 protected function toBase64DataURI(string $data, string|null $mime = null):string{
241 $mime ??= static::MIME_TYPE;
242
243 if($mime === ''){
244 $mime = $this->guessMimeType($data);
245 }
246
247 return sprintf('data:%s;base64,%s', $mime, base64_encode($data));
248 }
249
250 /**
251 * Guesses the mime type from the given $imageData
252 *
253 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
254 */
255 protected function guessMimeType(string $imageData):string{
256
257 if(!extension_loaded('fileinfo')){
258 throw new QRCodeOutputException('ext-fileinfo not loaded, cannot guess mime type');
259 }
260
261 $mime = (new finfo(FILEINFO_MIME_TYPE))->buffer($imageData);
262
263 if($mime === false){
264 throw new QRCodeOutputException('unable to detect mime type');
265 }
266
267 return $mime;
268 }
269
270 /**
271 * Saves the qr $data to a $file. If $file is null, nothing happens.
272 *
273 * @see file_put_contents()
274 * @see \chillerlan\QRCode\QROptions::$cachefile
275 *
276 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
277 */
278 protected function saveToFile(string $data, string|null $file = null):void{
279
280 if($file === null){
281 return;
282 }
283
284 if(!is_writable(dirname($file))){
285 throw new QRCodeOutputException(sprintf('Cannot write data to cache file: %s', $file));
286 }
287
288 if(file_put_contents($file, $data) === false){
289 throw new QRCodeOutputException(sprintf('Cannot write data to cache file: %s (file_put_contents error)', $file));
290 }
291 }
292
293 /**
294 * collects the modules per QRMatrix::M_* type, runs a transform method on each module and
295 * returns an array with the transformed modules.
296 *
297 * @see \chillerlan\QRCode\Output\QROutputAbstract::moduleTransform()
298 *
299 * @return array<int, mixed>
300 */
301 protected function collectModules():array{
302 $paths = [];
303
304 // collect the modules for each type
305 foreach($this->matrix->getMatrix() as $y => $row){
306 foreach($row as $x => $M_TYPE){
307 $M_TYPE_LAYER = $M_TYPE;
308
309 if($this->connectPaths && !$this->matrix->checkTypeIn($x, $y, $this->excludeFromConnect)){
310 // to connect paths we'll redeclare the $M_TYPE_LAYER to data only
311 $M_TYPE_LAYER = QRMatrix::M_DATA;
312
313 if($this->matrix->isDark($M_TYPE)){
314 $M_TYPE_LAYER = QRMatrix::M_DATA_DARK;
315 }
316 }
317
318 // collect the modules per $M_TYPE
319 $module = $this->moduleTransform($x, $y, $M_TYPE, $M_TYPE_LAYER);
320
321 if($module !== null){
322 $paths[$M_TYPE_LAYER][] = $module;
323 }
324 }
325 }
326
327 // beautify output
328 ksort($paths);
329
330 return $paths;
331 }
332
333 /**
334 * The transform callback for the module collector
335 *
336 * $x - current column
337 * $y - current row
338 * $M_TYPE - field value
339 * $M_TYPE_LAYER - (possibly modified) field value that acts as layer id ($paths array key)
340 *
341 * This method should return a value suitable for the current output class.
342 * It must return `null` for an empty value.
343 *
344 * @see \chillerlan\QRCode\Output\QROutputAbstract::collectModules()
345 */
346 protected function moduleTransform(int $x, int $y, int $M_TYPE, int $M_TYPE_LAYER):mixed{
347 return null;
348 }
349
350 }