ObjectHydrator   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 12
c 1
b 0
f 0
dl 0
loc 44
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A using() 0 4 1
A __construct() 0 5 2
A writeTo() 0 7 3
A default() 0 3 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydrator;
5
6
use Closure;
7
use Throwable;
8
9
/**
10
 * Hydrator 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 Hydrator
21
{
22
    /** @var Closure */
23
    private $setter;
24
25
    private function __construct(
26
        ?Closure $setter
27
    ) {
28
        $this->setter = $setter ?: function (string $attribute, $value): void {
29
            $this->$attribute = $value;
30
        };
31
    }
32
33
    /**
34
     * Produces an object hydrator with a default setter.
35
     *
36
     * @return Hydrator A hydrator that uses closure binding to write properties.
37
     */
38
    public static function default(): Hydrator
39
    {
40
        return new self(null);
41
    }
42
43
    /**
44
     * Produces an object hydrator with a custom setter.
45
     *
46
     * @param Closure   $setter The closure that writes the values.
47
     * @return Hydrator         A hydrator that uses a custom closure to write
48
     *                          properties.
49
     */
50
    public static function using(
51
        Closure $setter
52
    ): Hydrator {
53
        return new self($setter);
54
    }
55
56
    /** @inheritdoc */
57
    public function writeTo(object $target, array $input): void
58
    {
59
        foreach ($input as $attribute => $value) {
60
            try {
61
                $this->setter->call($target, $attribute, $value);
62
            } catch (Throwable $exception) {
63
                throw HydrationFailed::encountered($exception, $target);
64
            }
65
        }
66
    }
67
}
68