Hydrator::hydrate()   B
last analyzed

Complexity

Conditions 9
Paths 12

Size

Total Lines 42
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 22.3591

Importance

Changes 0
Metric Value
cc 9
eloc 29
nc 12
nop 3
dl 0
loc 42
ccs 14
cts 31
cp 0.4516
crap 22.3591
rs 8.0555
c 0
b 0
f 0
1
<?php
2
3
namespace Sf4\Populator;
4
5
use Sf4\Populator\Exception\HydratationException;
6
7
class Hydrator implements HydratorInterface
8
{
9
    /**
10
     * {@inheritDoc}
11
     */
12 3
    public function hydrate($data, $object, HydratorContextInterface $context)
13
    {
14 3
        foreach ($data as $key => $value) {
15 3
            if (null === $property = $context->getProperty($key)) {
16
                continue;
17
            }
18 3
            if ($property->isIgnored()) {
19
                continue;
20
            }
21 3
            $setter = $property->getSetter();
22 3
            $caller = array($object, $setter);
23 3
            if (!method_exists($object, $setter)) {
24 3
                if (!array_key_exists($key, get_object_vars($object))) {
25
                    throw new HydratationException(sprintf(
26
                        "Undefined setter method %s::%s for property '%s'",
27
                        get_class($object),
28
                        $setter,
29
                        $key
30
                    ));
31
                }
32 1
                $caller = function ($value) use ($object, $key) {
33 3
                    $object->$key = $value;
34 3
                };
35
            }
36 3
            if (null !== $subContext = $property->getContext()) {
37
                if (!is_array($value)) {
38
                    continue;
39
                }
40
                $subClass = $subContext->getClass();
41
                if (!class_exists($subClass)) {
42
                    throw new HydratationException(sprintf(
43
                        "Class %s does not exist for property '%s'",
44
                        $subClass,
45
                        $key
46
                    ));
47
                }
48
                $subObject = new $subClass;
49
                $value = $this->hydrate($value, $subObject, $subContext);
50
            }
51 3
            call_user_func_array($caller, array($value));
52
        }
53 3
        return $object;
54
    }
55
}
56