aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/chillerlan/php-qrcode/src/Output/QROutputAbstract.php
blob: a2757ac8cbcddddb6fabcab1169222d0b48694de (plain) (blame)
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
<?php
/**
 * Class QROutputAbstract
 *
 * @created      09.12.2015
 * @author       Smiley <smiley@chillerlan.net>
 * @copyright    2015 Smiley
 * @license      MIT
 */

namespace chillerlan\QRCode\Output;

use chillerlan\QRCode\Data\QRMatrix;
use chillerlan\Settings\SettingsContainerInterface;
use Closure;
use function base64_encode, dirname, file_put_contents, is_writable, ksort, sprintf;

/**
 * common output abstract
 */
abstract class QROutputAbstract implements QROutputInterface{

	/**
	 * the current size of the QR matrix
	 *
	 * @see \chillerlan\QRCode\Data\QRMatrix::getSize()
	 */
	protected int $moduleCount;

	/**
	 * the side length of the QR image (modules * scale)
	 */
	protected int $length;

	/**
	 * an (optional) array of color values for the several QR matrix parts
	 */
	protected array $moduleValues;

	/**
	 * the (filled) data matrix object
	 */
	protected QRMatrix $matrix;

	/**
	 * @var \chillerlan\Settings\SettingsContainerInterface|\chillerlan\QRCode\QROptions
	 */
	protected SettingsContainerInterface $options;

	/** @see \chillerlan\QRCode\QROptions::$scale */
	protected int $scale;
	/** @see \chillerlan\QRCode\QROptions::$connectPaths */
	protected bool $connectPaths;
	/** @see \chillerlan\QRCode\QROptions::$excludeFromConnect */
	protected array $excludeFromConnect;
	/** @see \chillerlan\QRCode\QROptions::$eol */
	protected string $eol;
	/** @see \chillerlan\QRCode\QROptions::$drawLightModules */
	protected bool $drawLightModules;
	/** @see \chillerlan\QRCode\QROptions::$drawCircularModules */
	protected bool $drawCircularModules;
	/** @see \chillerlan\QRCode\QROptions::$keepAsSquare */
	protected array $keepAsSquare;
	/** @see \chillerlan\QRCode\QROptions::$circleRadius */
	protected float $circleRadius;
	protected float $circleDiameter;

	/**
	 * QROutputAbstract constructor.
	 */
	public function __construct(SettingsContainerInterface $options, QRMatrix $matrix){
		$this->options = $options;
		$this->matrix  = $matrix;

		if($this->options->invertMatrix){
			$this->matrix->invert();
		}

		$this->copyVars();
		$this->setMatrixDimensions();
		$this->setModuleValues();
	}

	/**
	 * Creates copies of several QROptions values to avoid calling the magic getters
	 * in long loops for a significant performance increase.
	 *
	 * These variables are usually used in the "module" methods and are called up to 31329 times (at version 40).
	 */
	protected function copyVars():void{

		$vars = [
			'connectPaths',
			'excludeFromConnect',
			'eol',
			'drawLightModules',
			'drawCircularModules',
			'keepAsSquare',
			'circleRadius',
		];

		foreach($vars as $property){
			$this->{$property} = $this->options->{$property};
		}

		$this->circleDiameter = ($this->circleRadius * 2);
	}

	/**
	 * Sets/updates the matrix dimensions
	 *
	 * Call this method if you modify the matrix from within your custom module in case the dimensions have been changed
	 */
	protected function setMatrixDimensions():void{
		$this->moduleCount = $this->matrix->getSize();
		$this->scale       = $this->options->scale;
		$this->length      = ($this->moduleCount * $this->scale);
	}

	/**
	 * Returns a 2 element array with the current output width and height
	 *
	 * The type and units of the values depend on the output class. The default value is the current module count * scale.
	 */
	protected function getOutputDimensions():array{
		return [$this->length, $this->length];
	}

	/**
	 * Sets the initial module values
	 */
	protected function setModuleValues():void{

		// first fill the map with the default values
		foreach($this::DEFAULT_MODULE_VALUES as $M_TYPE => $defaultValue){
			$this->moduleValues[$M_TYPE] = $this->getDefaultModuleValue($defaultValue);
		}

		// now loop over the options values to replace defaults and add extra values
		foreach($this->options->moduleValues as $M_TYPE => $value){
			if($this::moduleValueIsValid($value)){
				$this->moduleValues[$M_TYPE] = $this->prepareModuleValue($value);
			}
		}

	}

	/**
	 * Prepares the value for the given input (return value depends on the output class)
	 *
	 * @param mixed $value
	 *
	 * @return mixed|null
	 */
	abstract protected function prepareModuleValue($value);

	/**
	 * Returns a default value for either dark or light modules (return value depends on the output class)
	 *
	 * @return mixed|null
	 */
	abstract protected function getDefaultModuleValue(bool $isDark);

	/**
	 * Returns the prepared value for the given $M_TYPE
	 *
	 * @return mixed return value depends on the output class
	 * @throws \chillerlan\QRCode\Output\QRCodeOutputException if $moduleValues[$M_TYPE] doesn't exist
	 */
	protected function getModuleValue(int $M_TYPE){

		if(!isset($this->moduleValues[$M_TYPE])){
			throw new QRCodeOutputException(sprintf('$M_TYPE %012b not found in module values map', $M_TYPE));
		}

		return $this->moduleValues[$M_TYPE];
	}

	/**
	 * Returns the prepared module value at the given coordinate [$x, $y] (convenience)
	 *
	 * @return mixed|null
	 */
	protected function getModuleValueAt(int $x, int $y){
		return $this->getModuleValue($this->matrix->get($x, $y));
	}

	/**
	 * Returns a base64 data URI for the given string and mime type
	 */
	protected function toBase64DataURI(string $data, ?string $mime = null):string{
		return sprintf('data:%s;base64,%s', ($mime ?? $this::MIME_TYPE), base64_encode($data));
	}

	/**
	 * Saves the qr $data to a $file. If $file is null, nothing happens.
	 *
	 * @see file_put_contents()
	 * @see \chillerlan\QRCode\QROptions::$cachefile
	 *
	 * @throws \chillerlan\QRCode\Output\QRCodeOutputException
	 */
	protected function saveToFile(string $data, ?string $file = null):void{

		if($file === null){
			return;
		}

		if(!is_writable(dirname($file))){
			throw new QRCodeOutputException(sprintf('Cannot write data to cache file: %s', $file));
		}

		if(file_put_contents($file, $data) === false){
			throw new QRCodeOutputException(sprintf('Cannot write data to cache file: %s (file_put_contents error)', $file));
		}
	}

	/**
	 * collects the modules per QRMatrix::M_* type and runs a $transform function on each module and
	 * returns an array with the transformed modules
	 *
	 * The transform callback is called with the following parameters:
	 *
	 *   $x            - current column
	 *   $y            - current row
	 *   $M_TYPE       - field value
	 *   $M_TYPE_LAYER - (possibly modified) field value that acts as layer id
	 */
	protected function collectModules(Closure $transform):array{
		$paths = [];

		// collect the modules for each type
		foreach($this->matrix->getMatrix() as $y => $row){
			foreach($row as $x => $M_TYPE){
				$M_TYPE_LAYER = $M_TYPE;

				if($this->connectPaths && !$this->matrix->checkTypeIn($x, $y, $this->excludeFromConnect)){
					// to connect paths we'll redeclare the $M_TYPE_LAYER to data only
					$M_TYPE_LAYER = QRMatrix::M_DATA;

					if($this->matrix->isDark($M_TYPE)){
						$M_TYPE_LAYER = QRMatrix::M_DATA_DARK;
					}
				}

				// collect the modules per $M_TYPE
				$module = $transform($x, $y, $M_TYPE, $M_TYPE_LAYER);

				if(!empty($module)){
					$paths[$M_TYPE_LAYER][] = $module;
				}
			}
		}

		// beautify output
		ksort($paths);

		return $paths;
	}

}