-
Notifications
You must be signed in to change notification settings - Fork 8
/
Serializer.php
59 lines (49 loc) · 1.54 KB
/
Serializer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
/**
* User: evgen-d
* Date: 08.10.14
* Time: 16:04
*/
namespace devgroup\arangodb;
use yii\base\Arrayable;
class Serializer
{
public static function encode($value, $options = 0)
{
$expressions = [];
$value = static::processData($value, $expressions, uniqid());
$json = json_encode($value, $options);
return empty($expressions) ? $json : strtr($json, $expressions);
}
protected static function processData($data, &$expressions, $expPrefix)
{
if (is_object($data)) {
if ($data instanceof AqlExpression) {
$token = "!{[$expPrefix=" . count($expressions) . ']}!';
$expressions['"' . $token . '"'] = $data->expression;
return $token;
} elseif ($data instanceof \JsonSerializable) {
$data = $data->jsonSerialize();
} elseif ($data instanceof Arrayable) {
$data = $data->toArray();
} else {
$result = [];
foreach ($data as $name => $value) {
$result[$name] = $value;
}
$data = $result;
}
if ($data === []) {
return new \stdClass();
}
}
if (is_array($data)) {
foreach ($data as $key => $value) {
if (is_array($value) || is_object($value)) {
$data[$key] = static::processData($value, $expressions, $expPrefix);
}
}
}
return $data;
}
}