Base::setHydrator()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
namespace GFG\DTOContext\Factory;
4
5
use GFG\DTOContext\DataWrapper;
6
7
abstract class Base implements FactoryInterface
8
{
9
    /**
10
     * @var HydratorInterface
11
     */
12
    private static $hydrator;
13
14
    /**
15
     * @return array
16
     */
17
    abstract public function getMappingList();
18
19
    /**
20
     * {@inheritdoc}
21
     */
22
    public function build(
23
        $contextName,
24
        DataWrapper\DataWrapperInterface $dataWrapper
25
    ) {
26
        $contextClass = $this->getMappedContext($contextName);
27
        return new $contextClass($dataWrapper);
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function rebuild(array $rawData, HydratorInterface $hydrator)
34
    {
35
        $hydrator->validateRawData($rawData);
36
        $this->checkMappedContext($rawData['name']);
37
38
        $dataWrapperName = $rawData['data_wrapper'];
39
40
        $context = $this->build(
41
            $rawData['name'],
42
            new $dataWrapperName($rawData['data'])
43
        );
44
45
        $hydrator->hydrate($context, $rawData);
46
47
        return $context;
48
    }
49
50
    /**
51
     * Return the mapped context class
52
     *
53
     * @param string $contextName
54
     * @return string
55
     */
56
    protected function getMappedContext($contextName)
57
    {
58
        $this->checkMappedContext($contextName);
59
        $mappingList = $this->getMappingList();
60
61
        return $mappingList[$contextName];
62
    }
63
64
    /**
65
     * Test a mapped context
66
     *
67
     * @param string $contextName
68
     * @return void
69
     */
70
    protected function checkMappedContext($contextName)
71
    {
72
        if (!array_key_exists($contextName, $this->getMappingList())) {
73
            throw new \InvalidArgumentException("invalid context name {$contextName}");
74
        }
75
    }
76
77
    /**
78
     * @return HydratorInterface
79
     */
80
    public function getHydrator()
81
    {
82
        if (!self::$hydrator) {
83
            self::$hydrator = new Hydrator();
84
        }
85
86
        return self::$hydrator;
87
    }
88
89
    /**
90
     * @param HydratorInterface $hydrator
91
     * @return Base
92
     */
93
    public function setHydrator(HydratorInterface $hydrator)
94
    {
95
        self::$hydrator = $hydrator;
96
        return $this;
97
    }
98
}
99