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

121 lines
3.0 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
*
2019-06-20 18:06:21 +03:00
* @param mixed $data
* @param string self::normalizeNamespace($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:
2019-06-20 18:06:21 +03:00
$deserialized = $serializer->fromArray(array_filter($data), self::normalizeNamespace($entityType), $context);
break;
case self::S_JSON:
2019-06-20 18:06:21 +03:00
$deserialized = $serializer->deserialize($data, self::normalizeNamespace($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-20 18:06:21 +03:00
/**
* @param string $namespace
*
* @return bool|string
*/
private static function normalizeNamespace(string $namespace)
{
if (substr($namespace, 0, 1) == '\\') {
return substr($namespace, 1);
} else {
return $namespace;
}
}
2019-06-10 16:24:22 +03:00
}