Completed
Push — master ( 407897...338945 )
by Jesse
05:08
created

CollectionHydrator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

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