-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathSerializer.php
More file actions
94 lines (84 loc) · 2.03 KB
/
Serializer.php
File metadata and controls
94 lines (84 loc) · 2.03 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
declare(strict_types=1);
namespace Hawk;
/**
* Class Serializer is used to serialize values before sending to the Hawk
*
* @package Hawk
*/
final class Serializer
{
/**
* Process any value and makes it safe (in appropriate format) to send to hawk
*
* @param $value
*
* @return string
*/
public function serializeValue($value): string
{
$encoded = json_encode($this->prepare($value), JSON_UNESCAPED_UNICODE);
if ($encoded === false) {
return '';
}
return $encoded;
}
/**
* Prepares value for encoding
*
* @param $value
*
* @return array|mixed|string
*/
private function prepare($value)
{
if (!is_object($value) && (is_array($value) || is_iterable($value))) {
$result = [];
foreach ($value as $key => $subValue) {
if (is_array($subValue) || is_iterable($subValue)) {
$result[$key] = $this->prepare($subValue);
} else {
$result[$key] = $this->transform($subValue);
}
}
return $result;
} else {
return $this->transform($value);
}
}
/**
* Transforms value to string or returns itself
*
* @param $value
*
* @return mixed|string
*/
private function transform($value)
{
if (is_null($value)) {
return 'null';
} elseif (is_callable($value)) {
return 'Closure';
} elseif (is_object($value)) {
return get_class($value);
} elseif (is_resource($value)) {
return 'Resource';
} else {
return $value;
}
}
/**
* Check array if it is associative
*
* @param array $array
*
* @return bool
*/
private function isAssoc(array $array): bool
{
if ([] === $array) {
return false;
}
return array_keys($array) !== range(0, count($array) - 1);
}
}