QRCode.php 7.6 KB

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