Byte.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. declare(strict_types=1);
  11. namespace chillerlan\QRCode\Data;
  12. use chillerlan\QRCode\Common\{BitBuffer, Mode};
  13. use function chr, ord;
  14. /**
  15. * 8-bit Byte mode, ISO-8859-1 or UTF-8
  16. *
  17. * ISO/IEC 18004:2000 Section 8.3.4
  18. * ISO/IEC 18004:2000 Section 8.4.4
  19. */
  20. final class Byte extends QRDataModeAbstract{
  21. public const DATAMODE = Mode::BYTE;
  22. public function getLengthInBits():int{
  23. return ($this->getCharCount() * 8);
  24. }
  25. public static function validateString(string $string):bool{
  26. return $string !== '';
  27. }
  28. public function write(BitBuffer $bitBuffer, int $versionNumber):static{
  29. $len = $this->getCharCount();
  30. $bitBuffer
  31. ->put(self::DATAMODE, 4)
  32. ->put($len, $this->getLengthBits($versionNumber))
  33. ;
  34. $i = 0;
  35. while($i < $len){
  36. $bitBuffer->put(ord($this->data[$i]), 8);
  37. $i++;
  38. }
  39. return $this;
  40. }
  41. /**
  42. * @inheritDoc
  43. *
  44. * @throws \chillerlan\QRCode\Data\QRCodeDataException
  45. */
  46. public function decodeSegment(BitBuffer $bitBuffer, int $versionNumber):string{
  47. $length = $bitBuffer->read($this->getLengthBits($versionNumber));
  48. if($bitBuffer->available() < (8 * $length)){
  49. throw new QRCodeDataException('not enough bits available'); // @codeCoverageIgnore
  50. }
  51. $readBytes = '';
  52. for($i = 0; $i < $length; $i++){
  53. $readBytes .= chr($bitBuffer->read(8));
  54. }
  55. return $readBytes;
  56. }
  57. }