Passed
Push — master ( c2f5d4...3262e6 )
by Jesse
02:44
created

ObjectHydrator.php$0 ➔ reflective()   A

Complexity

Conditions 3

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A ObjectHydrator::writeTo() 0 7 3
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydrator;
5
6
use Closure;
7
use Throwable;
8
9
/**
10
 * Hydrates an object from array input.
11
 *
12
 * Faster than a reflective object hydrator, but limited to properties that
13
 * can be accessed by the instance itself. That means this method cannot be
14
 * used in the context of inheritance when the parent class has private
15
 * properties.
16
 *
17
 * @package Stratadox\Hydrate
18
 * @author  Stratadox
19
 */
20
final class ObjectHydrator implements Hydrates
21
{
22
    private $setter;
23
24
    private function __construct(
25
        ?Closure $setter
26
    ) {
27
        $this->setter = $setter ?: function (string $attribute, $value): void {
28
            $this->$attribute = $value;
29
        };
30
    }
31
32
    /**
33
     * Produces an object hydrator with a default setter.
34
     *
35
     * @return Hydrates A hydrator that uses closure binding to write properties.
36
     */
37
    public static function default(): Hydrates
38
    {
39
        return new self(null);
40
    }
41
42
    /**
43
     * Produces an object hydrator with a custom setter.
44
     *
45
     * @param Closure   $setter The closure that writes the values.
46
     * @return Hydrates         A hydrator that uses a custom closure to write
47
     *                          properties.
48
     */
49
    public static function using(
50
        Closure $setter
51
    ): Hydrates {
52
        return new self($setter);
53
    }
54
55
    /** @inheritdoc */
56
    public function writeTo(object $target, array $data): void
57
    {
58
        foreach ($data as $attribute => $value) {
59
            try {
60
                $this->setter->call($target, $attribute, $value);
61
            } catch (Throwable $exception) {
62
                throw HydrationFailed::encountered($exception, $target);
63
            }
64
        }
65
    }
66
}
67