Packer.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace think\swoole\rpc;
  3. use RuntimeException;
  4. use think\swoole\rpc\packer\Buffer;
  5. use think\swoole\rpc\packer\File;
  6. class Packer
  7. {
  8. public const HEADER_SIZE = 8;
  9. public const HEADER_STRUCT = 'Nlength/Ntype';
  10. public const HEADER_PACK = 'NN';
  11. public const TYPE_BUFFER = 0;
  12. public const TYPE_FILE = 1;
  13. public static function pack($data, $type = self::TYPE_BUFFER)
  14. {
  15. return pack(self::HEADER_PACK, strlen($data), $type) . $data;
  16. }
  17. /**
  18. * @param $data
  19. * @return array<Buffer|File|string>
  20. */
  21. public static function unpack($data)
  22. {
  23. $header = unpack(self::HEADER_STRUCT, substr($data, 0, self::HEADER_SIZE));
  24. if ($header === false) {
  25. throw new RuntimeException('Invalid Header');
  26. }
  27. switch ($header['type']) {
  28. case Packer::TYPE_BUFFER:
  29. $handler = new Buffer($header['length']);
  30. break;
  31. case Packer::TYPE_FILE:
  32. $handler = new File($header['length']);
  33. break;
  34. default:
  35. throw new RuntimeException("unsupported data type: [{$header['type']}");
  36. }
  37. $data = substr($data, self::HEADER_SIZE);
  38. return [$handler, $data];
  39. }
  40. }