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

Reference   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 71
ccs 29
cts 29
cp 1
rs 10
c 1
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
B resolve() 0 34 6
A fromValue() 0 14 3
A __construct() 0 3 1
A reference() 0 3 1
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
    Lazy,
12
    Exception\ValueNotSupported,
13
    Exception\ArgumentNotProvided,
14
    Exception\ArgumentNotDefined,
15
    Exception\ReferenceNotFound
16
};
17
use Innmind\Immutable\{
18
    StreamInterface,
19
    Str
20
};
21
22
final class Reference implements Argument, HoldReference
23
{
24
    private $name;
25
26 47
    public function __construct(Name $name)
27
    {
28 47
        $this->name = $name;
29 47
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 34
    public static function fromValue($value, Arguments $arguments): Argument
35
    {
36 34
        if (!is_string($value)) {
37 8
            throw new ValueNotSupported;
38
        }
39
40 30
        $value = Str::of($value);
41
42 30
        if ((string) $value->substring(0, 1) !== '$') {
43 11
            throw new ValueNotSupported((string) $value);
44
        }
45
46 24
        return new self(new Name(
47 24
            (string) $value->substring(1)
48
        ));
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54 22
    public function resolve(
55
        StreamInterface $built,
56
        Services $services
57
    ): StreamInterface {
58
        try {
59 22
            return $built->add(
60 22
                $services->arguments()->get($this->name)
61
            );
62 20
        } catch (ArgumentNotProvided $e) {
63 10
            if ($e->argument()->hasDefault()) {
64 4
                return $built->add(new Lazy(
65 4
                    $e->argument()->default(),
66 4
                    $services
67
                ));
68
            }
69
70 8
            if ($e->argument()->optional()) {
71 3
                return $built->add(null);
72
            }
73
74 5
            throw $e;
75 15
        } catch (ArgumentNotDefined $e) {
76
            //pass
77
        }
78
79
        try {
80 15
            return $built->add(
81 15
                $services->dependencies()->lazy($this->name)
82
            );
83 14
        } catch (ReferenceNotFound $e) {
84
            //pass
85
        }
86
87 14
        return $built->add(new Lazy($this->name, $services));
88
    }
89
90 2
    public function reference(): Name
91
    {
92 2
        return $this->name;
93
    }
94
}
95