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

MappedHydrator::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
use Stratadox\Hydration\MapsProperties;
11
use Stratadox\Hydration\UnmappableInput;
12
13
/**
14
 * Hydrates an object from mapped array input.
15
 *
16
 * @package Stratadox\Hydrate
17
 * @author Stratadox
18
 */
19
final class MappedHydrator implements Hydrates
20
{
21
    private $class;
22
    private $properties;
23
    private $setter;
24
    private $object;
25
26
    private function __construct(
27
        ReflectionClass $reflector,
28
        MapsProperties $mapped,
29
        Closure $setter = null
30
    ) {
31
        $this->class = $reflector;
32
        $this->properties = $mapped;
33
        $this->setter = $setter ?: function (string $attribute, $value)
34
        {
35
            $this->$attribute = $value;
36
        };
37
    }
38
39
    public static function forThe(
40
        string $class,
41
        MapsProperties $mapped,
42
        Closure $setter = null
43
    ) : Hydrates
44
    {
45
        return new MappedHydrator(new ReflectionClass($class), $mapped, $setter);
46
    }
47
48
    public function fromArray(array $data)
49
    {
50
        try {
51
            $this->object = $this->class->newInstanceWithoutConstructor();
52
            $this->properties->writeData($this->object, $this->setter, $data);
53
            return $this->object;
54
        } catch (UnmappableInput $exception) {
55
            throw CouldNotMap::encountered($exception, $this->class);
56
        } finally {
57
            $this->object = null;
58
        }
59
    }
60
61
    public function currentInstance()
62
    {
63
        return $this->object;
64
    }
65
}
66