MutableCollectionHydrator::writeTo()   A
last analyzed

Complexity

Conditions 2
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 7
rs 10
1
<?php
2
declare(strict_types=1);
3
4
namespace Stratadox\Hydrator;
5
6
use ArrayAccess;
7
use Throwable;
8
use function assert;
9
10
/**
11
 * Hydrates a collection by calling its constructor with squashed array input.
12
 *
13
 * @author  Stratadox
14
 */
15
final class MutableCollectionHydrator 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 self();
29
    }
30
31
    /** @inheritdoc */
32
    public function writeTo(object $collection, array $input): void
33
    {
34
        try {
35
            assert($collection instanceof ArrayAccess);
36
            $this->write($collection, $input);
37
        } catch (Throwable $exception) {
38
            throw HydrationFailed::encountered($exception, $collection);
39
        }
40
    }
41
42
    private function write(ArrayAccess $collection, array $input): void
43
    {
44
        foreach ($input as $key => $value) {
45
            $collection[$key] = $value;
46
        }
47
    }
48
}
49