Completed
Push — master ( 2cee6a...9d457f )
by Jesse
03:27
created

SimpleHydrator::currentInstance()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Stratadox\Hydration\Hydrator;
6
7
use Closure;
8
use ReflectionClass;
9
use Stratadox\Hydration\Hydrates;
10
11
/**
12
 * Hydrates an object from array input.
13
 *
14
 * @package Stratadox\Hydrate
15
 * @author Stratadox
16
 */
17
final class SimpleHydrator implements Hydrates
18
{
19
    private $class;
20
    private $setter;
21
    private $object;
22
23
    private function __construct(
24
        ReflectionClass $reflector,
25
        Closure $setter = null
26
    ) {
27
        $this->class = $reflector;
28
        $this->setter = $setter ?: function (string $attribute, $value)
29
        {
30
            $this->$attribute = $value;
31
        };
32
    }
33
34
    public static function forThe(
35
        string $class,
36
        Closure $setter = null
37
    ) : Hydrates
38
    {
39
        return new SimpleHydrator(new ReflectionClass($class), $setter);
40
    }
41
42
    public function fromArray(array $data)
43
    {
44
        try {
45
            $this->object = $this->class->newInstanceWithoutConstructor();
46
            foreach ($data as $attribute => $value) {
47
                $this->setter->call($this->object, $attribute, $value);
48
            }
49
            return $this->object;
50
        } finally {
51
            $this->object = null;
52
        }
53
    }
54
55
    public function currentInstance()
56
    {
57
        return $this->object;
58
    }
59
}
60