Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace Thruway\Serializer;
- use MessagePack; // composer dep rybakit/msgpack": "^0.2.2",
- use Thruway\Message\Message;
- use Thruway\Message\MessageException;
- class MsgpackSerializer implements SerializerInterface {
- /**
- * @param Message $msg
- * @return mixed|string
- */
- public function serialize(Message $msg) {
- static $packer;
- if (!$packer) {
- $packer = new MessagePack\Packer();
- }
- return $packer->packArray(
- array_merge(
- [$msg->getMsgCode()],
- static::convertToArray($msg->getAdditionalMsgFields())
- )
- );
- }
- /**
- * @param mixed $serializedData
- * @return Message
- * @throws MessageException
- */
- public function deserialize($serializedData) {
- static $unpacker;
- if (!$unpacker) {
- $unpacker = new MessagePack\Unpacker();
- }
- $decoded = $unpacker->unpack($serializedData);
- $decoded[2] = static::convertToObject($decoded[2]);
- return Message::createMessageFromArray($decoded);
- }
- /**
- * @param object|array $data
- * @return object
- */
- public static function convertToObject($data) {
- if (is_array($data)) {
- return (object)array_map([static::class, 'convertToObject'], $data);
- } else {
- return $data;
- }
- }
- /**
- * @param object|array $data
- * @return array
- */
- public static function convertToArray($data) {
- if (is_array($data)) {
- foreach ($data as $key => $value) {
- if (is_array($value) || is_object($value)) {
- $data[$key] = static::convertToArray($value);
- }
- }
- return $data;
- } elseif (is_object($data)) {
- $result = [];
- foreach ($data as $key => $value) {
- $result[$key] = $value;
- }
- return static::convertToArray($result);
- }
- return [$data];
- }
- }
Add Comment
Please, Sign In to add comment