QRCode.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. <?php
  2. /**
  3. * Class QRCode
  4. *
  5. * @created 26.11.2015
  6. * @author Smiley <smiley@chillerlan.net>
  7. * @copyright 2015 Smiley
  8. * @license MIT
  9. *
  10. * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
  11. */
  12. declare(strict_types=1);
  13. namespace chillerlan\QRCode;
  14. use chillerlan\QRCode\Common\{
  15. ECICharset, GDLuminanceSource, IMagickLuminanceSource, LuminanceSourceInterface, MaskPattern, Mode
  16. };
  17. use chillerlan\QRCode\Data\{AlphaNum, Byte, ECI, Hanzi, Kanji, Number, QRData, QRDataModeInterface, QRMatrix};
  18. use chillerlan\QRCode\Decoder\{Decoder, DecoderResult};
  19. use chillerlan\QRCode\Output\{QRCodeOutputException, QROutputInterface};
  20. use chillerlan\Settings\SettingsContainerInterface;
  21. use function class_exists, class_implements, in_array, is_iterable, mb_convert_encoding, mb_internal_encoding;
  22. /**
  23. * Turns a text string into a Model 2 QR Code
  24. *
  25. * @see https://github.com/kazuhikoarase/qrcode-generator/tree/master/php
  26. * @see https://www.qrcode.com/en/codes/model12.html
  27. * @see https://www.swisseduc.ch/informatik/theoretische_informatik/qr_codes/docs/qr_standard.pdf
  28. * @see https://en.wikipedia.org/wiki/QR_code
  29. * @see https://www.thonky.com/qr-code-tutorial/
  30. */
  31. class QRCode{
  32. /**
  33. * The settings container
  34. */
  35. protected SettingsContainerInterface|QROptions $options;
  36. /**
  37. * A collection of one or more data segments of QRDataModeInterface instances to write
  38. *
  39. * @var \chillerlan\QRCode\Data\QRDataModeInterface[]
  40. */
  41. protected array $dataSegments = [];
  42. /**
  43. * The luminance source for the reader
  44. */
  45. protected string $luminanceSourceFQN = GDLuminanceSource::class;
  46. /**
  47. * QRCode constructor.
  48. *
  49. * @phpstan-param array<string, mixed> $options
  50. */
  51. public function __construct(SettingsContainerInterface|QROptions|iterable $options = new QROptions){
  52. $this->setOptions($options);
  53. }
  54. /**
  55. * Sets an options instance
  56. *
  57. * @phpstan-param array<string, mixed> $options
  58. */
  59. public function setOptions(SettingsContainerInterface|QROptions|iterable $options):static{
  60. if(is_iterable($options)){
  61. $options = new QROptions($options);
  62. }
  63. $this->options = $options;
  64. if($this->options->readerUseImagickIfAvailable){
  65. $this->luminanceSourceFQN = IMagickLuminanceSource::class;
  66. }
  67. return $this;
  68. }
  69. /**
  70. * Renders a QR Code for the given $data and QROptions, saves $file optionally
  71. */
  72. public function render(string|null $data = null, string|null $file = null):mixed{
  73. if($data !== null){
  74. foreach(Mode::INTERFACES as $dataInterface){
  75. if($dataInterface::validateString($data)){
  76. $this->addSegment(new $dataInterface($data));
  77. break;
  78. }
  79. }
  80. }
  81. return $this->renderMatrix($this->getQRMatrix(), $file);
  82. }
  83. /**
  84. * Renders a QR Code for the given QRMatrix and QROptions, saves $file optionally
  85. */
  86. public function renderMatrix(QRMatrix $matrix, string|null $file = null):mixed{
  87. return $this->initOutputInterface($matrix)->dump($file ?? $this->options->cachefile);
  88. }
  89. /**
  90. * Returns a QRMatrix object for the given $data and current QROptions
  91. */
  92. public function getQRMatrix():QRMatrix{
  93. $matrix = (new QRData($this->options, $this->dataSegments))->writeMatrix();
  94. $maskPattern = $this->options->maskPattern === MaskPattern::AUTO
  95. ? MaskPattern::getBestPattern($matrix)
  96. : new MaskPattern($this->options->maskPattern);
  97. $matrix->setFormatInfo($maskPattern)->mask($maskPattern);
  98. return $this->addMatrixModifications($matrix);
  99. }
  100. /**
  101. * add matrix modifications after mask pattern evaluation and before handing over to output
  102. */
  103. protected function addMatrixModifications(QRMatrix $matrix):QRMatrix{
  104. if($this->options->addLogoSpace){
  105. // check whether one of the dimensions was omitted
  106. $logoSpaceWidth = ($this->options->logoSpaceWidth ?? $this->options->logoSpaceHeight ?? 0);
  107. $logoSpaceHeight = ($this->options->logoSpaceHeight ?? $logoSpaceWidth);
  108. $matrix->setLogoSpace(
  109. $logoSpaceWidth,
  110. $logoSpaceHeight,
  111. $this->options->logoSpaceStartX,
  112. $this->options->logoSpaceStartY,
  113. );
  114. }
  115. if($this->options->addQuietzone){
  116. $matrix->setQuietZone($this->options->quietzoneSize);
  117. }
  118. return $matrix;
  119. }
  120. /**
  121. * initializes a fresh built-in or custom QROutputInterface
  122. *
  123. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  124. */
  125. protected function initOutputInterface(QRMatrix $matrix):QROutputInterface{
  126. $outputInterface = $this->options->outputInterface;
  127. if(empty($outputInterface) || !class_exists($outputInterface)){
  128. throw new QRCodeOutputException('invalid output class');
  129. }
  130. if(!in_array(QROutputInterface::class, class_implements($outputInterface), true)){
  131. throw new QRCodeOutputException('output class does not implement QROutputInterface');
  132. }
  133. /** @var \chillerlan\QRCode\Output\QROutputInterface $instance */
  134. $instance = new $outputInterface($this->options, $matrix);
  135. return $instance;
  136. }
  137. /**
  138. * Adds a data segment
  139. *
  140. * ISO/IEC 18004:2000 8.3.6 - Mixing modes
  141. * ISO/IEC 18004:2000 Annex H - Optimisation of bit stream length
  142. */
  143. public function addSegment(QRDataModeInterface $segment):static{
  144. $this->dataSegments[] = $segment;
  145. return $this;
  146. }
  147. /**
  148. * Clears the data segments array
  149. *
  150. * @codeCoverageIgnore
  151. */
  152. public function clearSegments():static{
  153. $this->dataSegments = [];
  154. return $this;
  155. }
  156. /**
  157. * Adds a numeric data segment
  158. *
  159. * ISO/IEC 18004:2000 8.3.2 - Numeric Mode
  160. */
  161. public function addNumericSegment(string $data):static{
  162. return $this->addSegment(new Number($data));
  163. }
  164. /**
  165. * Adds an alphanumeric data segment
  166. *
  167. * ISO/IEC 18004:2000 8.3.3 - Alphanumeric Mode
  168. */
  169. public function addAlphaNumSegment(string $data):static{
  170. return $this->addSegment(new AlphaNum($data));
  171. }
  172. /**
  173. * Adds a Kanji data segment (Japanese 13-bit double-byte characters, Shift-JIS)
  174. *
  175. * ISO/IEC 18004:2000 8.3.5 - Kanji Mode
  176. */
  177. public function addKanjiSegment(string $data):static{
  178. return $this->addSegment(new Kanji($data));
  179. }
  180. /**
  181. * Adds a Hanzi data segment (simplified Chinese 13-bit double-byte characters, GB2312/GB18030)
  182. *
  183. * GBT18284-2000 Hanzi Mode
  184. */
  185. public function addHanziSegment(string $data):static{
  186. return $this->addSegment(new Hanzi($data));
  187. }
  188. /**
  189. * Adds an 8-bit byte data segment
  190. *
  191. * ISO/IEC 18004:2000 8.3.4 - 8-bit Byte Mode
  192. */
  193. public function addByteSegment(string $data):static{
  194. return $this->addSegment(new Byte($data));
  195. }
  196. /**
  197. * Adds a standalone ECI designator
  198. *
  199. * The ECI designator must be followed by a Byte segment that contains the string encoded according to the given ECI charset
  200. *
  201. * ISO/IEC 18004:2000 8.3.1 - Extended Channel Interpretation (ECI) Mode
  202. */
  203. public function addEciDesignator(int $encoding):static{
  204. return $this->addSegment(new ECI($encoding));
  205. }
  206. /**
  207. * Adds an ECI data segment (including designator)
  208. *
  209. * The given string will be encoded from mb_internal_encoding() to the given ECI character set
  210. *
  211. * I hate this somehow, but I'll leave it for now
  212. *
  213. * @throws \chillerlan\QRCode\QRCodeException
  214. */
  215. public function addEciSegment(int $encoding, string $data):static{
  216. // validate the encoding id
  217. $eciCharset = new ECICharset($encoding);
  218. // get charset name
  219. $eciCharsetName = $eciCharset->getName();
  220. // convert the string to the given charset
  221. if($eciCharsetName !== null){
  222. $data = mb_convert_encoding($data, $eciCharsetName, mb_internal_encoding());
  223. return $this
  224. ->addEciDesignator($eciCharset->getID())
  225. ->addByteSegment($data)
  226. ;
  227. }
  228. throw new QRCodeException('unable to add ECI segment');
  229. }
  230. /**
  231. * Reads a QR Code from a given file
  232. */
  233. public function readFromFile(string $path):DecoderResult{
  234. return $this->readFromSource($this->luminanceSourceFQN::fromFile($path, $this->options));
  235. }
  236. /**
  237. * Reads a QR Code from the given data blob
  238. */
  239. public function readFromBlob(string $blob):DecoderResult{
  240. return $this->readFromSource($this->luminanceSourceFQN::fromBlob($blob, $this->options));
  241. }
  242. /**
  243. * Reads a QR Code from the given luminance source
  244. */
  245. public function readFromSource(LuminanceSourceInterface $source):DecoderResult{
  246. return (new Decoder($this->options))->decode($source);
  247. }
  248. }