MappedHydrator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 13
c 2
b 0
f 0
dl 0
loc 41
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A writeTo() 0 11 3
A using() 0 5 1
A __construct() 0 6 1
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
    /** @var Hydrator */
17
    private $hydrator;
18
    /** @var Mapping[] */
19
    private $properties;
20
21
    private function __construct(
22
        Hydrator $hydrator,
23
        Mapping ...$properties
24
    ) {
25
        $this->hydrator = $hydrator;
26
        $this->properties = $properties;
27
    }
28
29
    /**
30
     * Enables hydration mapping for a hydrator.
31
     *
32
     * @param Hydrator       $hydrator   The hydrator to decorate with mapping.
33
     * @param Mapping     ...$properties The mapping to apply to the input data.
34
     * @return Hydrator                  A decorated hydrator that maps the data.
35
     */
36
    public static function using(
37
        Hydrator $hydrator,
38
        Mapping ...$properties
39
    ): Hydrator {
40
        return new MappedHydrator($hydrator, ...$properties);
41
    }
42
43
    /** @inheritdoc */
44
    public function writeTo(object $target, array $input): void
45
    {
46
        $data = [];
47
        try {
48
            foreach ($this->properties as $property) {
49
                $data[$property->name()] = $property->value($input, $target);
50
            }
51
        } catch (MappingFailure $exception) {
52
            throw HydrationFailed::encountered($exception, $target);
53
        }
54
        $this->hydrator->writeTo($target, $data);
55
    }
56
}
57