Completed
Push — master ( c9d352...0a28f2 )
by Francesco
10:28
created

HydratableTrait   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 0
loc 55
c 0
b 0
f 0
wmc 8
lcom 1
cbo 2
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A preProcess() 0 4 1
B fromArray() 0 29 5
A toArray() 0 4 1
A getHydrator() 0 4 1
1
<?php
2
3
namespace Audiens\DoubleclickClient\entity;
4
5
use Audiens\DoubleclickClient\exceptions\ClientException;
6
use ReflectionObject;
7
use Zend\Hydrator\Reflection;
8
9
trait HydratableTrait
10
{
11
12
    public static function preProcess(array $objectArray): array
13
    {
14
        return $objectArray;
15
    }
16
17
    /**
18
     * @param array $objectArray
19
     *
20
     * @return static
21
     * @throws \Audiens\DoubleclickClient\exceptions\ClientException
22
     * @throws \Zend\Hydrator\Exception\BadMethodCallException
23
     */
24
    public static function fromArray(array $objectArray)
25
    {
26
        $objectArray = static::preProcess($objectArray);
27
28
        $object           = new self();
29
        $reflectionObject = new ReflectionObject($object);
30
        $props            = $reflectionObject->getProperties();
31
32
        $missingFields = [];
33
        foreach ($props as $prop) {
34
            if (strpos($prop->getDocComment(), '@required') === false) {
35
                continue;
36
            }
37
            $propName = $prop->getName();
38
39
40
            if (!isset($objectArray[$propName])) {
41
                $missingFields[] = $propName;
42
            }
43
        }
44
45
        if (\count($missingFields) > 0) {
46
            throw new ClientException('hydration: missing ['.implode(', ', $missingFields).']');
47
        }
48
49
        self::getHydrator()->hydrate($objectArray, $object);
50
51
        return $object;
52
    }
53
54
    public function toArray(): array
55
    {
56
        return self::getHydrator()->extract($this);
57
    }
58
59
    private static function getHydrator(): Reflection
60
    {
61
        return new Reflection();
62
    }
63
}
64