Last active
January 12, 2018 13:13
-
-
Save arleighdickerson/2d4592afd56c20233eabd1dde2a8fe2a to your computer and use it in GitHub Desktop.
Msgpack serialization support for voryx/thruway wamp2 implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment