QROutputAbstract.md.txt 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. # `QROutputAbstract`
  2. The abstract class `QROutputAbstract` contains several commonly used methods and properties and can be used as a basis for a custom output class.
  3. ## Properties
  4. ### `$options` and `$matrix`
  5. The `QROptions` and `QRMatrix` instances that were passed to the constructor of the output class.
  6. Both objects can be modified during runtime, for example to override settings or add matrix modifications.
  7. ### `$moduleCount`, `$scale` and `$length`
  8. These are convenience variables mostly to avoid multiple method calls to `QRMatrix::getSize()` and `QROptions::__get('scale')` inside loops,
  9. the `$length` is calculated from the aforementioned values (`$moduleCount * $scale`).
  10. The method `setMatrixDimensions()` can be called to update these 3 values after the matrix has been modified, e.g. by adding a quiet zone during output.
  11. ### `$moduleValues`
  12. The finalized map of `$M_TYPE` to value for the current output. This map is generated during invocation of the output class via `setModuleValues()`.
  13. ### Copies of `QROptions` values
  14. Some values from the `QROptions` instance are copied to properties to avoid calling the magic getters in long loops for a significant performance increase, e.g. in the module collector.
  15. Currently, the following values are copied via `copyVars()` during invocation: `$connectPaths`, `$excludeFromConnect`, `$eol`,
  16. `$drawLightModules`, `$drawCircularModules`, `$keepAsSquare`, `$circleRadius` (and additionally `$circleDiameter`).
  17. ## Methods
  18. ### `setModuleValues()`
  19. This method calls the abstract/interface methods `moduleValueIsValid()`, `prepareModuleValue()` and `getDefaultModuleValue()` to prepare the module values map.
  20. ### `moduleValueIsValid()`
  21. This method is declared in the `QROutputInterface` and needs to be implemented by the output class; it is `static` so that it can be called before invocation.
  22. The purpose is to determine whether the given `mixed` input is a valid module value for the current output class and returns `bool`.
  23. It's also useful to check values from `QROptions` such as `$bgColor` or `$transparencyColor`.
  24. Below is a pseudo implementation, check the code of the several output classes for actual implementations
  25. (e.g. [`QRImagick::moduleValueIsValid()`](https://github.com/chillerlan/php-qrcode/blob/4bd4b59fdec72397f5b1f70da9cadcb76764191b/src/Output/QRImagick.php#L68-L96))
  26. ```php
  27. class MyOutput extends QROutputAbstract{
  28. public static function moduleValueIsValid(mixed $value):bool{
  29. // check the type of the input value first
  30. if(!is_expected_type($value)){
  31. return false;
  32. }
  33. // do some more checks to determine the value
  34. if(!is_somehow_valid($value)){
  35. return false;
  36. }
  37. // looks like we got a match
  38. return true;
  39. }
  40. }
  41. ```
  42. ### `prepareModuleValue()`
  43. This method prepares the final replacement value from the given input.
  44. It might still be necessary to validate the given value despite it being checked earlier by `moduleValueIsValid()` -
  45. if nothing helps, this is a good place to throw an exception.
  46. Below a pseudo implementation example (see [`QRGdImage::prepareModuleValue()`](https://github.com/chillerlan/php-qrcode/blob/4bd4b59fdec72397f5b1f70da9cadcb76764191b/src/Output/QRGdImage.php#L138-L158)):
  47. ```php
  48. class MyOutput extends QROutputAbstract{
  49. protected function prepareModuleValue(mixed $value):mixed{
  50. // extended validation to make sure the values are valid for output
  51. // e.g. examine array values, clamp etc.
  52. if(!is_valid($value)){
  53. throw new QRCodeOutputException('invalid module value');
  54. }
  55. return $this->modifyValue($value);
  56. }
  57. }
  58. ```
  59. ### `getDefaultModuleValue()`
  60. Finally, setting a default value is required, in case a value for an `$M_TYPE` is not set or it's invalid.
  61. ```php
  62. class MyOutput extends QROutputAbstract{
  63. protected function getDefaultModuleValue(bool $isDark):mixed{
  64. $defaultValue = ($isDark === true)
  65. ? 'default value for dark'
  66. : 'default value for light';
  67. return $this->prepareModuleValue($defaultValue);
  68. }
  69. }
  70. ```
  71. ### `getModuleValue()` and `getModuleValueAt()`
  72. Both methods return a module value, the main difference is that `getModuleValueAt()` is a convenience method
  73. that makes an extra call to retrieve the `$M_TYPE` from the given matrix coordinate to return the value via `getModuleValue()`.
  74. A `foreach` loop over the matrix gives you the key (coordinate) *and* value of an array element:
  75. ```php
  76. class MyOutput extends QROutputAbstract{
  77. public function dump(string $file = null):string{
  78. $lines = [];
  79. foreach($this->matrix->getMatrix() as $y => $row){
  80. $lines[$y] = '';
  81. foreach($row as $x => $M_TYPE){
  82. $lines[$y] .= $this->getModuleValue($M_TYPE);
  83. }
  84. }
  85. return implode($this->options->eol, $lines);
  86. }
  87. }
  88. ```
  89. However, sometimes you might happen to use a `for` loop instead. The `for` loop leaves you only with the matrix coordinates, so you need to call `getModuleValueAt()`:
  90. ```php
  91. class MyOutput extends QROutputAbstract{
  92. public function dump(string $file = null):string{
  93. $lines = [];
  94. for($y = 0; $y < $this->moduleCount; $y++){
  95. $lines[$y] = '';
  96. for($x = 0; $x < $this->moduleCount; $x++){
  97. $lines[$y] .= $this->getModuleValueAt($x, $y);
  98. }
  99. }
  100. return implode($this->options->eol, $lines);
  101. }
  102. }
  103. ```
  104. ### `setMatrixDimensions()`
  105. As mentioned before, this method is supposed to set the values for the properties `$moduleCount`, `$scale` and `$length`.
  106. It is called in the constructor during invocation, but it might be necessary to call it again if the size of the matrix was changed in the output class
  107. (see [the round quiet zone example](https://github.com/chillerlan/php-qrcode/blob/99b1f9cf454ab1316cb643950a71caed3a6c0f5a/examples/svgRoundQuietzone.php#L38-L44) for a use case).
  108. ### `getOutputDimensions()`
  109. This method provides a simple way for consistent width/height values for the output (if applicable) which then can be changed by simply overriding this method.
  110. It returns a 2-element array that contains the values in a format that can be used by the output class, which is `QROutputAbstract::$length` (`$moduleCount * $scale`):
  111. ```php
  112. [$width, $height] = $this->getOutputDimensions();
  113. ```
  114. The output width and height can be changed in all places by simply overriding the method:
  115. ```php
  116. class MyOutput extends QROutputAbstract{
  117. protected function getOutputDimensions():array{
  118. // adjust the height in order to add something under the QR Code
  119. return [$this->length, ($this->length + 69)];
  120. }
  121. }
  122. ```
  123. ### `collectModules()`
  124. The module collector is particularly useful for plain text based file formats, for example the various markup languages like SVG and HTML or other structured file formats such as EPS.
  125. This method calls a method `moduleTransform()` internally with 4 parameters: the module coordinates `$x` and `$y`, the `$M_TYPE` and `$M_TYPE_LAYER`.
  126. The transform method should return a value that is valid for a single module of the QR matrix, or `null` if no transform was performed for the current module.
  127. The `$M_TYPE_LAYER` is a copy of the `$M_TYPE` that represents the array key of the returned array and that may have been reassigned in the collector to another path layer, e.g. through `QROptions::$connectPaths`.
  128. ```php
  129. class MyOutput extends QROutputAbstract{
  130. public function dump(string $file = null):string{
  131. // collect the modules for the path elements
  132. $paths = $this->collectModules();
  133. // loop over the paths
  134. foreach($paths as $M_TYPE_LAYER => &$path){
  135. if($path === []){
  136. continue;
  137. }
  138. $path = implode($this->options->eol, $path);
  139. }
  140. return implode($this->options->eol, $paths);
  141. }
  142. // this method must be implemented/overridden if your output class uses the module collector
  143. protected function moduleTransform(int $x, int $y, int $M_TYPE, int $M_TYPE_LAYER):string{
  144. return sprintf('%d %d %012b', $x, $y, $M_TYPE);
  145. }
  146. }
  147. ```
  148. Sometimes it can be necessary to override `collectModules()` in order to apply special effects such as random colors - you can find some implementations in [the SVG examples](https://github.com/chillerlan/php-qrcode/tree/main/examples).
  149. ### `saveToFile()` and `toBase64DataURI()`
  150. The void method `saveToFile()` takes a data blob and the `$file` given in `QROutputInterface::dump()` and save to the path if it is not `null` - the file path itself is not checked except for writability.
  151. The final output can be transformed to a [base64 data URI](https://en.wikipedia.org/wiki/Data_URI_scheme) with `toBase64DataURI()`, where the data blob and a valid mime type as parameters - the mime type is not checked.
  152. ```php
  153. class MyOutput extends QROutputAbstract{
  154. public function dump(string $file = null):string{
  155. $output = 'qrcode data string';
  156. // save the plain data to file
  157. $this->saveToFile($output, $file);
  158. // base64 encoding may be called optionally
  159. if($this->options->outputBase64){
  160. $output = $this->toBase64DataURI($output, 'text/plain');
  161. }
  162. return $output;
  163. }
  164. }
  165. ```