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

HydratableTrait::preProcess()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 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