Completed
Push — develop ( c0cf48...9f68ce )
by Baptiste
03:11
created

Argument   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
dl 0
loc 65
ccs 30
cts 30
cp 1
rs 10
c 0
b 0
f 0
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A name() 0 3 1
A __construct() 0 3 1
B resolve() 0 25 6
A fromValue() 0 22 3
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Compose\Definition\Dependency;
5
6
use Innmind\Compose\{
7
    Definition\Name,
8
    Services,
9
    Exception\ArgumentNotProvided,
10
    Exception\ArgumentNotDefined
11
};
12
use Innmind\Immutable\Str;
13
14
final class Argument
15
{
16
    private $name;
17
    private $value;
18
    private $reference;
19
20 9
    private function __construct(Name $name)
21
    {
22 9
        $this->name = $name;
23 9
    }
24
25 9
    public static function fromValue(Name $name, $value): self
26
    {
27 9
        if (!is_string($value)) {
28 1
            $self = new self($name);
29 1
            $self->value = $value;
30
31 1
            return $self;
32
        }
33
34 8
        $value = Str::of($value);
35
36 8
        if ((string) $value->substring(0, 1) !== '$') {
37 1
            $self = new self($name);
38 1
            $self->value = (string) $value;
39
40 1
            return $self;
41
        }
42
43 7
        $self = new self($name);
44 7
        $self->reference = new Name((string) $value->substring(1));
45
46 7
        return $self;
47
    }
48
49 9
    public function name(): Name
50
    {
51 9
        return $this->name;
52
    }
53
54 9
    public function resolve(Services $services)
55
    {
56 9
        if (!$this->reference instanceof Name) {
57 2
            return $this->value;
58
        }
59
60
        try {
61 7
            return $services->arguments()->get($this->reference);
62 5
        } catch (ArgumentNotProvided $e) {
63 3
            if ($e->argument()->hasDefault()) {
64 1
                return $services->build($e->argument()->default());
65
            }
66
67 2
            if ($e->argument()->optional()) {
68 1
                return null;
69
            }
70
71 1
            throw $e;
72 2
        } catch (ArgumentNotDefined $e) {
73
            //pass
74
        }
75
76
        // todo: allow to resolve services from other dependencies
77
78 2
        return $services->build($this->reference);
79
    }
80
}
81