Number.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Class Number
  4. *
  5. * @filesource Number.php
  6. * @created 26.11.2015
  7. * @package QRCode
  8. * @author Smiley <smiley@chillerlan.net>
  9. * @copyright 2015 Smiley
  10. * @license MIT
  11. */
  12. namespace codemasher\QRCode\Data;
  13. use codemasher\QRCode\BitBuffer;
  14. use codemasher\QRCode\QRCodeException;
  15. use codemasher\QRCode\QRConst;
  16. /**
  17. *
  18. */
  19. class Number extends QRDataBase implements QRDataInterface{
  20. /**
  21. * @var int
  22. */
  23. public $mode = QRConst::MODE_NUMBER;
  24. /**
  25. * @var array
  26. */
  27. protected $lengthBits = [10, 12, 14];
  28. /**
  29. * @param $buffer
  30. *
  31. * @return $this
  32. */
  33. public function write(BitBuffer &$buffer){
  34. $i = 0;
  35. while($i + 2 < $this->dataLength){
  36. $num = $this->parseInt(substr($this->data, $i, 3));
  37. $buffer->put($num, 10);
  38. $i += 3;
  39. }
  40. if($i < $this->dataLength){
  41. if($this->dataLength - $i === 1){
  42. $num = $this->parseInt(substr($this->data, $i, $i + 1));
  43. $buffer->put($num, 4);
  44. }
  45. else if($this->dataLength - $i === 2){
  46. $num = $this->parseInt(substr($this->data, $i, $i + 2));
  47. $buffer->put($num, 7);
  48. }
  49. }
  50. return $this;
  51. }
  52. /**
  53. * @param string $string
  54. *
  55. * @return int
  56. * @throws \codemasher\QRCode\QRCodeException
  57. */
  58. protected function parseInt($string){
  59. $num = 0;
  60. $len = strlen($string);
  61. for($i = 0; $i < $len; $i++){
  62. $c = ord($string[$i]);
  63. $ord0 = ord('0');
  64. if(ord('0') <= $c && $c <= ord('9')){
  65. $c = $c - $ord0;
  66. }
  67. else{
  68. throw new QRCodeException('illegal char: '.$c);
  69. }
  70. $num = $num * 10 + $c;
  71. }
  72. return $num;
  73. }
  74. }