QROutputAbstract.php 8.3 KB

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