1
0
mirror of synced 2024-11-29 14:26:02 +03:00
mg-bot-api-client-php/src/Serializer.php

107 lines
2.6 KiB
PHP
Raw Normal View History

2019-06-10 16:24:22 +03:00
<?php
/**
* PHP version 7.0
*
* Serializer
*
* @package RetailCrm\Common
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
namespace RetailCrm\Common;
use JMS\Serializer\DeserializationContext;
use JMS\Serializer\SerializationContext;
use JMS\Serializer\SerializerBuilder;
2019-06-10 16:24:22 +03:00
/**
* PHP version 7.0
*
* Serializer class
*
* @package RetailCrm\Common
* @author retailCRM <integration@retailcrm.ru>
* @license https://opensource.org/licenses/MIT MIT License
* @link http://help.retailcrm.pro/docs/Developers
*/
class Serializer
{
const S_ARRAY = 'array';
const S_JSON = 'json';
2019-06-10 16:24:22 +03:00
/**
* Serialize given object to JSON or Array
*
* @param object $request
* @param int $serialize
*
* @return array|string
*/
public static function serialize($request, $serialize = self::S_JSON)
{
$serialized = null;
$serializer = SerializerBuilder::create()->build();
$context = self::getContext();
2019-06-10 16:24:22 +03:00
switch ($serialize) {
case self::S_ARRAY:
$serialized = $serializer->toArray($request, $context);
2019-06-10 16:24:22 +03:00
break;
case self::S_JSON:
default:
$serialized = $serializer->serialize($request, $serialize, $context);
2019-06-10 16:24:22 +03:00
break;
}
return $serialized;
}
/**
* Deserialize given array or JSON to object
*
* @param $data
* @param $entityType
* @param string $from
*
* @return array|object|null
*/
public static function deserialize($data, $entityType, $from = self::S_JSON)
{
$deserialized = null;
$serializer = SerializerBuilder::create()->build();
$context = self::getContext(true);
switch ($from) {
case self::S_ARRAY:
$deserialized = $serializer->fromArray(array_filter($data), $entityType, $context);
break;
case self::S_JSON:
$deserialized = $serializer->deserialize($data, $entityType, $from, $context);
break;
}
return $deserialized;
}
/**
* @param bool $deserialization (default: false)
*
* @return DeserializationContext|SerializationContext
*/
private static function getContext(bool $deserialization = false)
{
if ($deserialization) {
$context = new DeserializationContext();
} else {
$context = new SerializationContext();
}
$context->setSerializeNull(false);
return $context;
}
2019-06-10 16:24:22 +03:00
}