ImmutableCollectionHydrator::write()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydrator;
5
6
use ReflectionException;
7
use ReflectionMethod;
8
use Throwable;
9
10
/**
11
 * Hydrates a collection by calling its constructor with squashed array input.
12
 *
13
 * @author  Stratadox
14
 */
15
final class ImmutableCollectionHydrator implements Hydrator
16
{
17
    private function __construct()
18
    {
19
    }
20
21
    /**
22
     * Produces a collection hydrator.
23
     *
24
     * @return Hydrator A hydrator that calls the constructor through reflection.
25
     */
26
    public static function default(): Hydrator
27
    {
28
        return new ImmutableCollectionHydrator();
29
    }
30
31
    /** @inheritdoc */
32
    public function writeTo(object $collection, array $input): void
33
    {
34
        try {
35
            $this->write($collection, $input);
36
        } catch (Throwable $exception) {
37
            throw HydrationFailed::encountered($exception, $collection);
38
        }
39
    }
40
41
    /** @throws ReflectionException */
42
    private function write(object $collection, array $input): void
43
    {
44
        $constructor = new ReflectionMethod($collection, '__construct');
45
        $constructor->setAccessible(true);
46
        $constructor->invoke($collection, ...$input);
47
    }
48
}
49