Completed
Push — master ( 5ba1dc...b85ec4 )
by Tomasz
02:09
created

AbstractFormat::doUnserialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.6666
cc 2
eloc 5
nc 2
nop 3
crap 2
1
<?php
2
namespace Thunder\Serializard\Format;
3
4
use Thunder\Serializard\HydratorContainer\HydratorContainerInterface as Hydrators;
5
use Thunder\Serializard\NormalizerContainer\NormalizerContainerInterface as Normalizers;
6
7
/**
8
 * @author Tomasz Kowalczyk <[email protected]>
9
 */
10
abstract class AbstractFormat implements FormatInterface
11
{
12 8
    protected function doSerialize($var, Normalizers $handlers, array $state = array(), array $classes = array())
13
    {
14 8
        if(is_object($var)) {
15 8
            $class = get_class($var);
16 8
            $handler = $handlers->getHandler($class);
17
18 8
            if(null === $handler) {
19 1
                throw new \RuntimeException(sprintf('No serialization handler for class %s!', $class));
20
            }
21
22 7
            $hash = spl_object_hash($var);
23 7
            $classes[] = get_class($var);
24 7
            if(isset($state[$hash])) {
25 3
                throw new \RuntimeException('Nesting cycle: '.implode(' -> ', $classes));
26
            }
27 7
            $state[$hash] = 1;
28
29 7
            return $this->doSerialize(call_user_func_array($handler, array($var)), $handlers, $state, $classes);
30
        }
31
32 7
        if(is_array($var)) {
33 6
            $return = array();
34 6
            foreach($var as $key => $value) {
35 6
                $return[$key] = $this->doSerialize($value, $handlers, $state, $classes);
36 6
            }
37
38 6
            return $return;
39
        }
40
41 7
        return $var;
42
    }
43
44 3
    protected function doUnserialize($var, $class, Hydrators $hydrators)
45
    {
46 3
        $handler = $hydrators->getHandler($class);
47 3
        if(null === $handler) {
48 1
            throw new \RuntimeException(sprintf('No unserialization handler for class %s!', $class));
49
        }
50
51 2
        return call_user_func_array($handler, array($var, $hydrators));
52
    }
53
}
54