Passed
Push — master ( 01c6a8...5a4258 )
by Jesse
09:00
created

NumberedProxyCollectionMapping   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

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

5 Methods

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