Passed
Push — develop ( 7d2249...4ccadf )
by Baptiste
02:09
created

Unwind::reference()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Compose\Definition\Service\Argument;
5
6
use Innmind\Compose\{
7
    Definition\Service\Argument,
8
    Definition\Service\Arguments,
9
    Definition\Name,
10
    Services,
11
    Exception\ValueNotSupported,
12
    Exception\ArgumentNotProvided,
13
    Exception\ArgumentNotDefined,
14
    Exception\ReferenceNotFound
15
};
16
use Innmind\Immutable\{
17
    Str,
18
    StreamInterface,
19
    Stream
20
};
21
22
final class Unwind implements Argument, HoldReference
23
{
24
    private $name;
25
26 11
    private function __construct(Name $name)
27
    {
28 11
        $this->name = $name;
29 11
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 23
    public static function fromValue($value, Arguments $arguments): Argument
35
    {
36 23
        if (!is_string($value)) {
37 8
            throw new ValueNotSupported;
38
        }
39
40 18
        $value = Str::of($value);
41
42 18
        if ((string) $value->substring(0, 4) !== '...$') {
43 8
            throw new ValueNotSupported((string) $value);
44
        }
45
46 11
        return new self(new Name(
47 11
            (string) $value->substring(4)
48
        ));
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 7
    public function resolve(
55
        StreamInterface $built,
56
        Services $services
57
    ): StreamInterface {
58
        try {
59 7
            return $built->append(Stream::of(
60 7
                'mixed',
61 7
                ...$services->arguments()->get($this->name)
62
            ));
63 6
        } catch (ArgumentNotProvided $e) {
64 4
            if ($e->argument()->hasDefault()) {
65 1
                return $built->append(Stream::of(
66 1
                    'mixed',
67 1
                    ...$services->build($e->argument()->default())
68
                ));
69
            }
70
71 3
            if ($e->argument()->optional()) {
72 2
                return $built;
73
            }
74
75 1
            throw $e;
76 2
        } catch (ArgumentNotDefined $e) {
77
            //pass
78
        }
79
80
        try {
81 2
            return $built->append(Stream::of(
82 2
                'mixed',
83 2
                ...$services->dependencies()->build($this->name)
84
            ));
85 1
        } catch (ReferenceNotFound $e) {
86
            //pass
87
        }
88
89 1
        return $built->append(Stream::of(
90 1
            'mixed',
91 1
            ...$services->build($this->name)
92
        ));
93
    }
94
95 1
    public function reference(): Name
96
    {
97 1
        return $this->name;
98
    }
99
}
100