RelationCollectionMapping   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
c 1
b 0
f 0
dl 0
loc 58
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A itemsFromArray() 0 7 2
A value() 0 11 3
A __construct() 0 8 1
A inProperty() 0 6 1
A name() 0 3 1
1
<?php declare(strict_types=1);
2
3
namespace Stratadox\Hydration\Mapping\Relation;
4
5
use Stratadox\Deserializer\DeserializationFailure;
6
use Stratadox\Deserializer\Deserializer;
7
use Stratadox\HydrationMapping\Mapping;
8
use Throwable;
9
10
final class RelationCollectionMapping implements Mapping
11
{
12
    /** @var string */
13
    private $name;
14
    /** @var Deserializer */
15
    private $collection;
16
    /** @var Deserializer */
17
    private $item;
18
19
    private function __construct(
20
        string $name,
21
        Deserializer $collection,
22
        Deserializer $item
23
    ) {
24
        $this->name = $name;
25
        $this->collection = $collection;
26
        $this->item = $item;
27
    }
28
29
    public static function inProperty(
30
        string $name,
31
        Deserializer $collection,
32
        Deserializer $item
33
    ): Mapping {
34
        return new self($name, $collection, $item);
35
    }
36
37
    public function name(): string
38
    {
39
        return $this->name;
40
    }
41
42
    public function value(array $data, $owner = null)
43
    {
44
        try {
45
            $objects = $this->itemsFromArray($data);
46
        } catch (Throwable $exception) {
47
            throw RelationMappingFailure::encountered($this, $exception);
48
        }
49
        try {
50
            return $this->collection->from($objects);
51
        } catch (Throwable $exception) {
52
            throw CollectionMappingFailure::encountered($this, $exception);
53
        }
54
    }
55
56
    /**
57
     * @param array[] $data
58
     * @return object[]
59
     * @throws DeserializationFailure
60
     */
61
    private function itemsFromArray(array $data): array
62
    {
63
        $objects = [];
64
        foreach ($data as $objectData) {
65
            $objects[] = $this->item->from($objectData);
66
        }
67
        return $objects;
68
    }
69
}
70