Passed
Push — master ( 6895b1...424f48 )
by Jesse
08:53
created

MappedHydrator::using()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydrator;
5
6
use Stratadox\HydrationMapping\Mapping;
7
use Stratadox\HydrationMapping\MappingFailure;
8
9
/**
10
 * Applies hydration mapping to the input data before hydrating.
11
 *
12
 * @author Stratadox
13
 */
14
final class MappedHydrator implements Hydrator
15
{
16
    private $hydrator;
17
    private $properties;
18
19
    private function __construct(
20
        Hydrator $hydrator,
21
        Mapping ...$properties
22
    ) {
23
        $this->hydrator = $hydrator;
24
        $this->properties = $properties;
25
    }
26
27
    /**
28
     * Enables hydration mapping for a hydrator.
29
     *
30
     * @param Hydrator       $hydrator   The hydrator to decorate with mapping.
31
     * @param Mapping     ...$properties The mapping to apply to the input data.
32
     * @return Hydrator                  A decorated hydrator that maps the data.
33
     */
34
    public static function using(
35
        Hydrator $hydrator,
36
        Mapping ...$properties
37
    ): Hydrator {
38
        return new MappedHydrator($hydrator, ...$properties);
39
    }
40
41
    /** @inheritdoc */
42
    public function writeTo(object $target, array $input): void
43
    {
44
        $data = [];
45
        try {
46
            foreach ($this->properties as $property) {
47
                $data[$property->name()] = $property->value($input, $target);
48
            }
49
        } catch (MappingFailure $exception) {
50
            throw HydrationFailed::encountered($exception, $target, $input);
51
        }
52
        $this->hydrator->writeTo($target, $data);
53
    }
54
}
55