Guest User

Untitled

a guest
Jan 22nd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. <?php
  2.  
  3. namespace Thruway\Serializer;
  4.  
  5. use MessagePack; // composer dep rybakit/msgpack": "^0.2.2",
  6. use Thruway\Message\Message;
  7. use Thruway\Message\MessageException;
  8.  
  9. class MsgpackSerializer implements SerializerInterface {
  10. /**
  11. * @param Message $msg
  12. * @return mixed|string
  13. */
  14. public function serialize(Message $msg) {
  15. static $packer;
  16. if (!$packer) {
  17. $packer = new MessagePack\Packer();
  18. }
  19. return $packer->packArray(
  20. array_merge(
  21. [$msg->getMsgCode()],
  22. static::convertToArray($msg->getAdditionalMsgFields())
  23. )
  24. );
  25. }
  26.  
  27. /**
  28. * @param mixed $serializedData
  29. * @return Message
  30. * @throws MessageException
  31. */
  32. public function deserialize($serializedData) {
  33. static $unpacker;
  34. if (!$unpacker) {
  35. $unpacker = new MessagePack\Unpacker();
  36. }
  37. $decoded = $unpacker->unpack($serializedData);
  38. $decoded[2] = static::convertToObject($decoded[2]);
  39. return Message::createMessageFromArray($decoded);
  40. }
  41.  
  42. /**
  43. * @param object|array $data
  44. * @return object
  45. */
  46. public static function convertToObject($data) {
  47. if (is_array($data)) {
  48. return (object)array_map([static::class, 'convertToObject'], $data);
  49. } else {
  50. return $data;
  51. }
  52. }
  53.  
  54. /**
  55. * @param object|array $data
  56. * @return array
  57. */
  58. public static function convertToArray($data) {
  59. if (is_array($data)) {
  60. foreach ($data as $key => $value) {
  61. if (is_array($value) || is_object($value)) {
  62. $data[$key] = static::convertToArray($value);
  63. }
  64. }
  65. return $data;
  66. } elseif (is_object($data)) {
  67. $result = [];
  68. foreach ($data as $key => $value) {
  69. $result[$key] = $value;
  70. }
  71. return static::convertToArray($result);
  72. }
  73. return [$data];
  74. }
  75. }
Add Comment
Please, Sign In to add comment