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

CollectionHydrator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 28
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 5
dl 0
loc 28
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A write() 0 5 1
A default() 0 3 1
A __construct() 0 2 1
A writeTo() 0 8 2
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