1
|
|
|
<?php |
2
|
|
|
namespace Thunder\Serializard\Format; |
3
|
|
|
|
4
|
|
|
use Thunder\Serializard\Exception\SerializationFailureException; |
5
|
|
|
use Thunder\Serializard\HydratorContainer\HydratorContainerInterface as Hydrators; |
6
|
|
|
use Thunder\Serializard\NormalizerContainer\NormalizerContainerInterface as Normalizers; |
7
|
|
|
use Thunder\Serializard\NormalizerContext\NormalizerContextInterface; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* @author Tomasz Kowalczyk <[email protected]> |
11
|
|
|
*/ |
12
|
|
|
abstract class AbstractFormat implements FormatInterface |
13
|
|
|
{ |
14
|
12 |
|
protected function doSerialize($var, Normalizers $handlers, NormalizerContextInterface $context, array $state = [], array $classes = []) |
15
|
|
|
{ |
16
|
12 |
|
if(\is_object($var)) { |
17
|
11 |
|
$class = \get_class($var); |
18
|
|
|
// FIXME consider local handler cache to improve performance (solve parent class fallback issue) |
19
|
11 |
|
$handler = $handlers->getHandler($class); |
20
|
|
|
|
21
|
10 |
|
$hash = spl_object_hash($var); |
22
|
10 |
|
$classes[] = $class; |
23
|
10 |
|
if(isset($state[$hash])) { |
24
|
3 |
|
throw SerializationFailureException::fromCycle($classes); |
25
|
|
|
} |
26
|
10 |
|
$state[$hash] = 1; |
27
|
|
|
|
28
|
10 |
|
return $this->doSerialize($handler($var, $context), $handlers, $context->withParent($var), $state, $classes); |
29
|
|
|
} |
30
|
|
|
|
31
|
11 |
|
if(\is_array($var)) { |
32
|
8 |
|
$return = []; |
33
|
8 |
|
foreach($var as $key => $value) { |
34
|
8 |
|
$return[$key] = $this->doSerialize($value, $handlers, $context, $state, $classes); |
35
|
|
|
} |
36
|
|
|
|
37
|
8 |
|
return $return; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
// FIXME: just return scalars, exception for different types like resources or streams |
41
|
|
|
|
42
|
11 |
|
return $var; |
43
|
|
|
} |
44
|
|
|
|
45
|
5 |
|
protected function doUnserialize($var, $class, Hydrators $hydrators) |
46
|
|
|
{ |
47
|
5 |
|
return \call_user_func($hydrators->getHandler($class), $var, $hydrators); |
48
|
|
|
} |
49
|
|
|
} |
50
|
|
|
|