Hydrator::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
1
<?php
2
namespace Redbox\Hydrate;
3
4
class Hydrator
5
{
6
    /**
7
     * @var null
8
     */
9
    protected $destination = null;
10
11
    /**
12
     * @var array
13
     */
14
    protected $source = [];
15
16
    /**
17
     * Hydrator constructor.
18
     * @param $destination
19
     * @internal param null $subject
20
     */
21 10
    public function __construct($destination)
22
    {
23 10
        $this->destination = $destination;
24 10
    }
25
26
    /**
27
     * @param $destination
28
     * @return Hydrator
29
     */
30 8
    public static function hydrate($destination)
31
    {
32 8
        return new Hydrator($destination);
33
    }
34
35
    /**
36
     * @param array $source
37
     * @return null
38
     * @throws \Exception
39
     */
40 10
    public function with($source = [])
41
    {
42 10
        if (is_array($source) === false) {
43 2
            throw new \Exception('Source should be an array');
44
        }
45
46 8
        $this->source = $source;
47
48 8
        return $this->run();
49
    }
50
51
    /**
52
     * @return null
53
     * @throws \Exception
54
     */
55 8
    private function run()
56
    {
57 8
        if (is_object($this->destination) === false) {
58 2
            throw new \Exception('Destination is not an object');
59
        }
60
61
        /** @var \ReflectionObject $reflection */
62 6
        $reflection = new \ReflectionObject($this->destination);
63
64
        /** @var \ReflectionProperty[] $properties */
65 6
        $properties = $reflection->getProperties();
66
67 6
        foreach ($properties as $property) {
68 6
            $name = $property->getName();
69
70 6
            if (isset($this->source[$name])) {
71 6
                $value = $this->source[$name];
72 6
                $readonly = ($property->isPublic() === false && $property->isStatic() === false);
73
74 6
                if ($readonly === true) {
75 6
                    $property->setAccessible(true);
76 6
                }
77
78 6
                $property->setValue($this->destination, $value);
79 6
            }
80 6
        }
81 6
        return $this->destination;
82
    }
83
}