ArrayStrategy   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 1 Features 0
Metric Value
eloc 16
c 3
b 1
f 0
dl 0
loc 50
ccs 16
cts 16
cp 1
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 5
    public function __construct(array $config)
32
    {
33 5
        $this->config = $config;
34 5
    }
35
36
    /**
37
     * @param object $object
38
     *
39
     * @return void
40
     */
41 5
    public function initialize(object $object): void
42
    {
43 5
        $this->mappings = iterator_to_array($this->generateMappings($object));
44 5
    }
45
46
    /**
47
     * @param object $object
48
     *
49
     * @throws ReflectionException
50
     *
51
     * @return Generator
52
     */
53 5
    private function generateMappings(object $object): Generator
54
    {
55 5
        foreach ($this->config as $key => $value) {
56 5
            $k = $value === true ? $key : $value;
57 5
            $hasProperty = property_exists($object, $k);
58 5
            $hasMethod = method_exists($object, $k);
59 5
            if ($hasProperty || $hasMethod) {
60 5
                $hydrationKey = new HydrationKey($key);
61 5
                yield $key => $hasProperty
62 5
                    ? new PropertyMapping(new ReflectionProperty($object, $k), $hydrationKey)
63 4
                    : new MethodMapping(new ReflectionMethod($object, $value), $hydrationKey);
64
            }
65
        }
66 5
    }
67
}
68