AlphaNum.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. /**
  3. * Class AlphaNum
  4. *
  5. * @filesource AlphaNum.php
  6. * @created 25.11.2015
  7. * @package chillerlan\QRCode\Data
  8. * @author Smiley <smiley@chillerlan.net>
  9. * @copyright 2015 Smiley
  10. * @license MIT
  11. */
  12. namespace chillerlan\QRCode\Data;
  13. use chillerlan\QRCode\{BitBuffer, QRConst};
  14. /**
  15. *
  16. */
  17. class AlphaNum extends QRDataAbstract{
  18. const CHAR_MAP = [
  19. 36 => ' ',
  20. 37 => '$',
  21. 38 => '%',
  22. 39 => '*',
  23. 40 => '+',
  24. 41 => '-',
  25. 42 => '.',
  26. 43 => '/',
  27. 44 => ':',
  28. ];
  29. /**
  30. * @var int
  31. */
  32. public $mode = QRConst::MODE_ALPHANUM;
  33. /**
  34. * @var array
  35. */
  36. protected $lengthBits = [9, 11, 13];
  37. /**
  38. * @param \chillerlan\QRCode\BitBuffer $buffer
  39. *
  40. * @return void
  41. */
  42. public function write(BitBuffer &$buffer){
  43. $i = 0;
  44. while($i + 1 < $this->dataLength){
  45. $buffer->put($this->getCharCode($this->data[$i]) * 45 + $this->getCharCode($this->data[$i + 1]), 11);
  46. $i += 2;
  47. }
  48. if($i < $this->dataLength){
  49. $buffer->put($this->getCharCode($this->data[$i]), 6);
  50. }
  51. }
  52. /**
  53. * @param string $chr
  54. *
  55. * @return int
  56. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  57. */
  58. private static function getCharCode(string $chr):int {
  59. $chr = ord($chr);
  60. switch(true){
  61. case ord('0') <= $chr && $chr <= ord('9'): return $chr - ord('0');
  62. case ord('A') <= $chr && $chr <= ord('Z'): return $chr - ord('A') + 10;
  63. default:
  64. foreach(self::CHAR_MAP as $i => $c){
  65. if(ord($c) === $chr){
  66. return $i;
  67. }
  68. }
  69. }
  70. throw new QRCodeDataException('illegal char: '.$chr);
  71. }
  72. }