GenericAwaker   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 8
eloc 20
dl 0
loc 62
c 0
b 0
f 0
rs 10
ccs 22
cts 22
cp 1

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A awake() 0 27 4
A populate() 0 14 3
1
<?php
2
/**
3
 * File was created 07.10.2015 06:35
4
 */
5
6
namespace PeekAndPoke\Component\Slumber\Core\Codec;
7
8
use PeekAndPoke\Component\Slumber\Core\LookUp\EntityConfig;
9
use PeekAndPoke\Component\Slumber\Core\LookUp\EntityConfigReader;
10
11
/**
12
 * @author Karsten J. Gerber <[email protected]>
13
 */
14
class GenericAwaker implements Awaker
15
{
16
    /** @var EntityConfigReader */
17
    protected $entityConfigLookUp;
18
19
    /**
20
     * @param EntityConfigReader $entityConfigLookUp
21
     */
22 374
    public function __construct(EntityConfigReader $entityConfigLookUp)
23
    {
24 374
        $this->entityConfigLookUp = $entityConfigLookUp;
25 374
    }
26
27
    /**
28
     * @param mixed            $data
29
     * @param \ReflectionClass $cls
30
     *
31
     * @return mixed|null
32
     */
33 14
    public function awake($data, \ReflectionClass $cls)
34
    {
35
        // read the config for the given class
36 14
        $config = $this->entityConfigLookUp->getEntityConfig($cls);
37
38 14
        if ($config === null) {
39 1
            return null;
40
        }
41
42
        // create an instance
43 13
        $subject = $config->getCreator()->create($data);
44
45
        // if we do not get an instance we return nothing
46 13
        if ($subject === null) {
47 1
            return null;
48
        }
49
50
        // NOTICE: creating the instance can change the type (e.g. for polymorphic mapping)
51
        //         Therefore we need to read the config again if the type has changed
52 12
        if ($cls->name !== \get_class($subject)) {
53 4
            $config = $this->entityConfigLookUp->getEntityConfig(new \ReflectionClass($subject));
54
        }
55
56
        // populate the result
57 12
        $this->populate($subject, $data, $config);
58
59 12
        return $subject;
60
    }
61
62 12
    private function populate($subject, $data, EntityConfig $config)
63
    {
64
        // get the properties we need to map
65 12
        $entries = $config->getMarkedProperties();
66
67 12
        foreach ($entries as $entry) {
68
            // awake using the alias name
69 12
            $alias = $entry->alias;
70
71
            // do we have data for that property
72 12
            if (isset($data[$alias])) {
73 10
                $entry->propertyAccess->set(
74 10
                    $subject,
75 12
                    $entry->mapper->awake($this, $data[$alias])
76
                );
77
            }
78
        }
79 12
    }
80
}
81