Completed
Push — master ( 9d457f...574e8f )
by Jesse
02:48
created

MappedHydrator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
dl 0
loc 59
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A fromArray() 0 11 3
A __construct() 0 12 2
A forThe() 0 12 2
1
<?php
2
3
declare(strict_types = 1);
4
5
namespace Stratadox\Hydrator;
6
7
use Closure;
8
use ReflectionClass;
9
use Stratadox\HydrationMapping\MapsProperties;
10
use Throwable;
11
12
/**
13
 * Hydrates an object from mapped array input.
14
 *
15
 * @package Stratadox\Hydrate
16
 * @author Stratadox
17
 */
18
final class MappedHydrator implements Hydrates
19
{
20
    private $class;
21
    private $properties;
22
    private $setter;
23
    private $observer;
24
25
    private function __construct(
26
        ReflectionClass $reflector,
27
        MapsProperties $mapped,
28
        ObservesHydration $observer,
29
        ?Closure $setter
30
    ) {
31
        $this->class = $reflector;
32
        $this->properties = $mapped;
33
        $this->observer = $observer;
34
        $this->setter = $setter ?: function (string $attribute, $value)
35
        {
36
            $this->$attribute = $value;
37
        };
38
    }
39
40
    /**
41
     * Creates a new mapped hydrator for a class.
42
     *
43
     * @param string                 $class    The class to hydrate.
44
     * @param MapsProperties         $mapped   The mappings for the properties.
45
     * @param Closure|null           $setter   The closure that writes the values.
46
     * @param ObservesHydration|null $observer Object that gets updated with the
47
     *                                         hydrating instance.
48
     * @return self                            The mapped hydrator.
49
     */
50
    public static function forThe(
51
        string $class,
52
        MapsProperties $mapped,
53
        Closure $setter = null,
54
        ObservesHydration $observer = null
55
    ) : self
56
    {
57
        return new self(
58
            new ReflectionClass($class),
59
            $mapped,
60
            $observer ?: BlindObserver::add(),
61
            $setter
62
        );
63
    }
64
65
    /** @inheritdoc */
66
    public function fromArray(array $data)
67
    {
68
        try {
69
            $object = $this->class->newInstanceWithoutConstructor();
70
            $this->observer->hydrating($object);
71
            foreach ($this->properties as $property) {
72
                $this->setter->call($object, $property->name(), $property->value($data));
73
            }
74
            return $object;
75
        } catch (Throwable $exception) {
76
            throw HydrationFailed::encountered($exception, $this->class);
77
        }
78
    }
79
}
80