Byte.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Class Byte
  4. *
  5. * @created 25.11.2015
  6. * @author Smiley <smiley@chillerlan.net>
  7. * @copyright 2015 Smiley
  8. * @license MIT
  9. */
  10. namespace chillerlan\QRCode\Data;
  11. use chillerlan\QRCode\Common\{BitBuffer, Mode};
  12. use function chr, ord;
  13. /**
  14. * Byte mode, ISO-8859-1 or UTF-8
  15. *
  16. * ISO/IEC 18004:2000 Section 8.3.4
  17. * ISO/IEC 18004:2000 Section 8.4.4
  18. */
  19. final class Byte extends QRDataModeAbstract{
  20. /**
  21. * @inheritDoc
  22. */
  23. protected static int $datamode = Mode::BYTE;
  24. /**
  25. * @inheritDoc
  26. */
  27. public function getLengthInBits():int{
  28. return $this->getCharCount() * 8;
  29. }
  30. /**
  31. * @inheritDoc
  32. */
  33. public static function validateString(string $string):bool{
  34. return !empty($string);
  35. }
  36. /**
  37. * @inheritDoc
  38. */
  39. public function write(BitBuffer $bitBuffer, int $versionNumber):void{
  40. $len = $this->getCharCount();
  41. $bitBuffer
  42. ->put($this::$datamode, 4)
  43. ->put($len, Mode::getLengthBitsForVersion($this::$datamode, $versionNumber))
  44. ;
  45. $i = 0;
  46. while($i < $len){
  47. $bitBuffer->put(ord($this->data[$i]), 8);
  48. $i++;
  49. }
  50. }
  51. /**
  52. * @inheritDoc
  53. *
  54. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  55. */
  56. public static function decodeSegment(BitBuffer $bitBuffer, int $versionNumber):string{
  57. $length = $bitBuffer->read(Mode::getLengthBitsForVersion(self::$datamode, $versionNumber));
  58. if($bitBuffer->available() < 8 * $length){
  59. throw new QRCodeDataException('not enough bits available');
  60. }
  61. $readBytes = '';
  62. for($i = 0; $i < $length; $i++){
  63. $readBytes .= chr($bitBuffer->read(8));
  64. }
  65. return $readBytes;
  66. }
  67. }