QRCode.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. <?php
  2. /**
  3. * Class QRCode
  4. *
  5. * @filesource QRCode.php
  6. * @created 26.11.2015
  7. * @package chillerlan\QRCode
  8. * @author Smiley <smiley@chillerlan.net>
  9. * @copyright 2015 Smiley
  10. * @license MIT
  11. */
  12. namespace chillerlan\QRCode;
  13. use chillerlan\QRCode\Data\{
  14. AlphaNum, Byte, Kanji, MaskPatternTester, Number, QRCodeDataException, QRDataInterface, QRMatrix
  15. };
  16. use chillerlan\QRCode\Output\{
  17. QRCodeOutputException, QRImage, QRMarkup, QROutputInterface, QRString
  18. };
  19. use chillerlan\Traits\ClassLoader;
  20. /**
  21. * Turns a text string into a Model 2 QR Code
  22. *
  23. * @link https://github.com/kazuhikoarase/qrcode-generator/tree/master/php
  24. * @link http://www.qrcode.com/en/codes/model12.html
  25. * @link http://www.thonky.com/qr-code-tutorial/
  26. */
  27. class QRCode{
  28. use ClassLoader;
  29. /**
  30. * API constants
  31. */
  32. const OUTPUT_MARKUP_HTML = 'html';
  33. const OUTPUT_MARKUP_SVG = 'svg';
  34. # const OUTPUT_MARKUP_XML = 'xml'; // anyone?
  35. const OUTPUT_IMAGE_PNG = 'png';
  36. const OUTPUT_IMAGE_JPG = 'jpg';
  37. const OUTPUT_IMAGE_GIF = 'gif';
  38. const OUTPUT_STRING_JSON = 'json';
  39. const OUTPUT_STRING_TEXT = 'text';
  40. const VERSION_AUTO = -1;
  41. const MASK_PATTERN_AUTO = -1;
  42. const ECC_L = 0b01; // 7%.
  43. const ECC_M = 0b00; // 15%.
  44. const ECC_Q = 0b11; // 25%.
  45. const ECC_H = 0b10; // 30%.
  46. const DATA_NUMBER = 0b0001;
  47. const DATA_ALPHANUM = 0b0010;
  48. const DATA_BYTE = 0b0100;
  49. const DATA_KANJI = 0b1000;
  50. const ECC_MODES = [
  51. self::ECC_L => 0,
  52. self::ECC_M => 1,
  53. self::ECC_Q => 2,
  54. self::ECC_H => 3,
  55. ];
  56. const DATA_MODES = [
  57. self::DATA_NUMBER => 0,
  58. self::DATA_ALPHANUM => 1,
  59. self::DATA_BYTE => 2,
  60. self::DATA_KANJI => 3,
  61. ];
  62. const OUTPUT_MODES = [
  63. QRMarkup::class => [
  64. self::OUTPUT_MARKUP_SVG,
  65. self::OUTPUT_MARKUP_HTML,
  66. ],
  67. QRImage::class => [
  68. self::OUTPUT_IMAGE_PNG,
  69. self::OUTPUT_IMAGE_GIF,
  70. self::OUTPUT_IMAGE_JPG,
  71. ],
  72. QRString::class => [
  73. self::OUTPUT_STRING_JSON,
  74. self::OUTPUT_STRING_TEXT,
  75. ]
  76. ];
  77. /**
  78. * @var \chillerlan\QRCode\QROptions
  79. */
  80. protected $options;
  81. /**
  82. * @var \chillerlan\QRCode\Data\QRDataInterface
  83. */
  84. protected $dataInterface;
  85. /**
  86. * QRCode constructor.
  87. *
  88. * @param \chillerlan\QRCode\QROptions|null $options
  89. */
  90. public function __construct(QROptions $options = null){
  91. mb_internal_encoding('UTF-8');
  92. $this->setOptions($options ?? new QROptions);
  93. }
  94. /**
  95. * Sets the options, called internally by the constructor
  96. *
  97. * @param \chillerlan\QRCode\QROptions $options
  98. *
  99. * @return \chillerlan\QRCode\QRCode
  100. * @throws \chillerlan\QRCode\QRCodeException
  101. */
  102. public function setOptions(QROptions $options):QRCode{
  103. if(!array_key_exists($options->eccLevel, self::ECC_MODES)){
  104. throw new QRCodeException('Invalid error correct level: '.$options->eccLevel);
  105. }
  106. if(!is_array($options->imageTransparencyBG || count($options->imageTransparencyBG) < 3)){
  107. $options->imageTransparencyBG = [255, 255, 255];
  108. }
  109. $options->version = (int)$options->version;
  110. // clamp min/max version number
  111. $options->versionMin = (int)min($options->versionMin, $options->versionMax);
  112. $options->versionMax = (int)max($options->versionMin, $options->versionMax);
  113. $this->options = $options;
  114. return $this;
  115. }
  116. /**
  117. * Renders a QR Code for the given $data and QROptions
  118. *
  119. * @param string $data
  120. *
  121. * @return mixed
  122. */
  123. public function render(string $data){
  124. return $this->initOutputInterface($data)->dump();
  125. }
  126. /**
  127. * Returns a QRMatrix object for the given $data and current QROptions
  128. *
  129. * @param string $data
  130. *
  131. * @return \chillerlan\QRCode\Data\QRMatrix
  132. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  133. */
  134. public function getMatrix(string $data):QRMatrix {
  135. $data = trim($data);
  136. if(empty($data)){
  137. throw new QRCodeDataException('QRCode::getMatrix() No data given.');
  138. }
  139. $this->dataInterface = $this->initDataInterface($data);
  140. $maskPattern = $this->options->maskPattern === self::MASK_PATTERN_AUTO
  141. ? $this->getBestMaskPattern()
  142. : max(7, min(0, (int)$this->options->maskPattern));
  143. $matrix = $this
  144. ->dataInterface
  145. ->initMatrix($maskPattern)
  146. ;
  147. if((bool)$this->options->addQuietzone){
  148. $matrix->setQuietZone($this->options->quietzoneSize);
  149. }
  150. return $matrix;
  151. }
  152. /**
  153. * shoves a QRMatrix through the MaskPatternTester to find the lowest penalty mask pattern
  154. *
  155. * @see \chillerlan\QRCode\Data\MaskPatternTester
  156. *
  157. * @return int
  158. */
  159. protected function getBestMaskPattern():int{
  160. $penalties = [];
  161. $tester = new MaskPatternTester;
  162. for($testPattern = 0; $testPattern < 8; $testPattern++){
  163. $matrix = $this
  164. ->dataInterface
  165. ->initMatrix($testPattern, true);
  166. $tester->setMatrix($matrix);
  167. $penalties[$testPattern] = $tester->testPattern();
  168. }
  169. return array_search(min($penalties), $penalties, true);
  170. }
  171. /**
  172. * returns a fresh QRDataInterface for the given $data
  173. *
  174. * @param string $data
  175. *
  176. * @return \chillerlan\QRCode\Data\QRDataInterface
  177. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  178. */
  179. public function initDataInterface(string $data):QRDataInterface{
  180. $DATA_MODES = [
  181. Number::class => 'Number',
  182. AlphaNum::class => 'AlphaNum',
  183. Kanji::class => 'Kanji',
  184. Byte::class => 'Byte',
  185. ];
  186. foreach($DATA_MODES as $dataInterface => $mode){
  187. if(call_user_func_array([$this, 'is'.$mode], [$data]) === true){
  188. return $this->loadClass($dataInterface, QRDataInterface::class, $this->options, $data);
  189. }
  190. }
  191. throw new QRCodeDataException('invalid data type'); // @codeCoverageIgnore
  192. }
  193. /**
  194. * returns a fresh (built-in) QROutputInterface
  195. *
  196. * @param string $data
  197. *
  198. * @return \chillerlan\QRCode\Output\QROutputInterface
  199. * @throws \chillerlan\QRCode\Output\QRCodeOutputException
  200. */
  201. protected function initOutputInterface(string $data):QROutputInterface{
  202. foreach(self::OUTPUT_MODES as $outputInterface => $modes){
  203. if(in_array($this->options->outputType, $modes, true)){
  204. return $this->loadClass($outputInterface, QROutputInterface::class, $this->options, $this->getMatrix($data));
  205. }
  206. }
  207. throw new QRCodeOutputException('invalid output type');
  208. }
  209. /**
  210. * checks if a string qualifies as numeric
  211. *
  212. * @param string $string
  213. *
  214. * @return bool
  215. */
  216. public function isNumber(string $string):bool {
  217. $len = strlen($string);
  218. $map = str_split('0123456789');
  219. for($i = 0; $i < $len; $i++){
  220. if(!in_array($string[$i], $map, true)){
  221. return false;
  222. }
  223. }
  224. return true;
  225. }
  226. /**
  227. * checks if a string qualifies as alphanumeric
  228. *
  229. * @param string $string
  230. *
  231. * @return bool
  232. */
  233. public function isAlphaNum(string $string):bool {
  234. $len = strlen($string);
  235. for($i = 0; $i < $len; $i++){
  236. if(!in_array($string[$i], AlphaNum::CHAR_MAP, true)){
  237. return false;
  238. }
  239. }
  240. return true;
  241. }
  242. /**
  243. * checks if a string qualifies as Kanji
  244. *
  245. * @param string $string
  246. *
  247. * @return bool
  248. */
  249. public function isKanji(string $string):bool {
  250. $i = 0;
  251. $len = strlen($string);
  252. while($i + 1 < $len){
  253. $c = ((0xff&ord($string[$i])) << 8)|(0xff&ord($string[$i + 1]));
  254. if(!($c >= 0x8140 && $c <= 0x9FFC) && !($c >= 0xE040 && $c <= 0xEBBF)){
  255. return false;
  256. }
  257. $i += 2;
  258. }
  259. return !($i < $len);
  260. }
  261. /**
  262. * a dummy
  263. *
  264. * @codeCoverageIgnore
  265. *
  266. * @param $data
  267. *
  268. * @return bool
  269. */
  270. protected function isByte(string $data):bool{
  271. return !empty($data);
  272. }
  273. }