Test Failed
Push — master ( f2f49d...52ea81 )
by Matt
02:18
created

ArrayStrategy   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
eloc 16
c 2
b 1
f 0
dl 0
loc 49
rs 10
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A initialize() 0 3 1
A __construct() 0 3 1
A generateMappings() 0 11 6
1
<?php
2
3
namespace Maiorano\ObjectHydrator\Strategies;
4
5
use Generator;
6
use Maiorano\ObjectHydrator\Attributes\HydrationKey;
7
use Maiorano\ObjectHydrator\Mappings\HydrationMappingInterface;
8
use Maiorano\ObjectHydrator\Mappings\MethodMapping;
9
use Maiorano\ObjectHydrator\Mappings\PropertyMapping;
10
use ReflectionException;
11
use ReflectionMethod;
12
use ReflectionProperty;
13
14
class ArrayStrategy implements HydrationStrategyInterface
15
{
16
    use DirectKeyAccessTrait;
17
    use RecursiveCheckTrait;
18
19
    /**
20
     * @var array
21
     */
22
    private array $config;
23
    /**
24
     * @var HydrationMappingInterface[]
25
     */
26
    private array $mappings;
27
28
    /**
29
     * @param array $config
30
     */
31
    public function __construct(array $config)
32
    {
33
        $this->config = $config;
34
    }
35
36
    /**
37
     * @param object $object
38
     *
39
     * @return void
40
     */
41
    public function initialize(object $object): void
42
    {
43
        $this->mappings = iterator_to_array($this->generateMappings($object));
44
    }
45
46
47
    /**
48
     * @param object $object
49
     * @return Generator
50
     * @throws ReflectionException
51
     */
52
    private function generateMappings(object $object): Generator
53
    {
54
        foreach ($this->config as $key => $value) {
55
            $k = $value === true ? $key : $value;
56
            $hasProperty = property_exists($object, $k);
57
            $hasMethod = method_exists($object, $k);
58
            if ($hasProperty || $hasMethod) {
59
                $hydrationKey = new HydrationKey($k);
60
                yield $k => $hasProperty
61
                    ? new PropertyMapping(new ReflectionProperty($object, $value), $hydrationKey)
62
                    : new MethodMapping(new ReflectionMethod($object, $value), $hydrationKey);
63
            }
64
        }
65
    }
66
}
67