JsonLengthPacker.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\JsonRpc\Packer;
  12. use Hyperf\Contract\PackerInterface;
  13. class JsonLengthPacker implements PackerInterface
  14. {
  15. /**
  16. * @var string
  17. */
  18. protected $type;
  19. /**
  20. * @var int
  21. */
  22. protected $length;
  23. protected $defaultOptions = [
  24. 'package_length_type' => 'N',
  25. 'package_body_offset' => 4,
  26. ];
  27. public function __construct(array $options = [])
  28. {
  29. $options = array_merge($this->defaultOptions, $options['settings'] ?? []);
  30. $this->type = $options['package_length_type'];
  31. $this->length = $options['package_body_offset'];
  32. }
  33. public function pack($data): string
  34. {
  35. $data = json_encode($data, JSON_UNESCAPED_UNICODE);
  36. return pack($this->type, strlen($data)) . $data;
  37. }
  38. public function unpack(string $data)
  39. {
  40. $data = substr($data, $this->length);
  41. if (! $data) {
  42. return null;
  43. }
  44. return json_decode($data, true);
  45. }
  46. }