AlphaNum.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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\QRCode;
  14. /**
  15. * Alphanumeric mode: 0 to 9, A to Z, space, $ % * + - . / :
  16. */
  17. class AlphaNum extends QRDataAbstract{
  18. const CHAR_MAP = [
  19. '0', '1', '2', '3', '4', '5', '6', '7',
  20. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
  21. 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
  22. 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
  23. 'W', 'X', 'Y', 'Z', ' ', '$', '%', '*',
  24. '+', '-', '.', '/', ':',
  25. ];
  26. /**
  27. * @inheritdoc
  28. */
  29. protected $datamode = QRCode::DATA_ALPHANUM;
  30. /**
  31. * @inheritdoc
  32. */
  33. protected $lengthBits = [9, 11, 13];
  34. /**
  35. * @inheritdoc
  36. */
  37. protected function write(string $data){
  38. for($i = 0; $i + 1 < $this->strlen; $i += 2){
  39. $this->bitBuffer->put($this->getCharCode($data[$i]) * 45 + $this->getCharCode($data[$i + 1]), 11);
  40. }
  41. if($i < $this->strlen){
  42. $this->bitBuffer->put($this->getCharCode($data[$i]), 6);
  43. }
  44. }
  45. /**
  46. * @param string $chr
  47. *
  48. * @return int
  49. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  50. */
  51. protected function getCharCode(string $chr):int {
  52. $i = array_search($chr, self::CHAR_MAP);
  53. if($i !== false){
  54. return $i;
  55. }
  56. throw new QRCodeDataException('illegal char: "'.$chr.'" ['.ord($chr).']');
  57. }
  58. }