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