1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Innmind\Compose; |
5
|
|
|
|
6
|
|
|
use Innmind\Compose\{ |
7
|
|
|
Definition\Argument, |
8
|
|
|
Definition\Name, |
9
|
|
|
Exception\MissingArgument, |
10
|
|
|
Exception\ArgumentNotProvided |
11
|
|
|
}; |
12
|
|
|
use Innmind\Immutable\{ |
13
|
|
|
Sequence, |
14
|
|
|
MapInterface, |
15
|
|
|
Map |
16
|
|
|
}; |
17
|
|
|
|
18
|
|
|
final class Arguments |
19
|
|
|
{ |
20
|
|
|
private $arguments; |
21
|
|
|
private $values; |
22
|
|
|
|
23
|
10 |
|
public function __construct(Argument ...$arguments) |
24
|
|
|
{ |
25
|
10 |
|
$this->arguments = Sequence::of(...$arguments)->reduce( |
26
|
10 |
|
new Map('string', Argument::class), |
27
|
10 |
|
static function(Map $arguments, Argument $argument): Map { |
28
|
8 |
|
return $arguments->put( |
29
|
8 |
|
(string) $argument->name(), |
30
|
8 |
|
$argument |
31
|
|
|
); |
32
|
10 |
|
} |
33
|
|
|
); |
34
|
10 |
|
$this->values = new Map('string', 'mixed'); |
35
|
10 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param MapInterface<string, mixed> $values |
39
|
|
|
* |
40
|
|
|
* @throws MissingArgument |
41
|
|
|
*/ |
42
|
9 |
|
public function bind(MapInterface $values): self |
43
|
|
|
{ |
44
|
|
|
if ( |
45
|
9 |
|
(string) $values->keyType() !== 'string' || |
46
|
9 |
|
(string) $values->valueType() !== 'mixed' |
47
|
|
|
) { |
48
|
1 |
|
throw new \TypeError('Argument 1 must be of type MapInterface<string, mixed>'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$this |
52
|
8 |
|
->arguments |
53
|
8 |
|
->filter(static function(string $name, Argument $argument): bool { |
54
|
8 |
|
return !$argument->optional() && !$argument->hasDefault(); |
55
|
8 |
|
}) |
56
|
8 |
|
->foreach(static function(string $name) use ($values): void { |
57
|
6 |
|
if (!$values->contains($name)) { |
|
|
|
|
58
|
1 |
|
throw new MissingArgument($name); |
59
|
|
|
} |
60
|
8 |
|
}); |
61
|
|
|
$this |
62
|
7 |
|
->arguments |
63
|
7 |
|
->filter(static function(string $name) use ($values): bool { |
64
|
7 |
|
return $values->contains($name); |
|
|
|
|
65
|
7 |
|
}) |
66
|
7 |
|
->foreach(static function(string $name, Argument $argument) use ($values): void { |
67
|
5 |
|
$argument->validate($values->get($name)); |
|
|
|
|
68
|
7 |
|
}); |
69
|
|
|
|
70
|
6 |
|
$self = clone $this; |
71
|
6 |
|
$self->values = $values; |
72
|
|
|
|
73
|
6 |
|
return $self; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @throws ArgumentNotProvided |
78
|
|
|
* |
79
|
|
|
* @return mixed |
80
|
|
|
*/ |
81
|
5 |
|
public function get(Name $name) |
82
|
|
|
{ |
83
|
5 |
|
if (!$this->values->contains((string) $name)) { |
84
|
3 |
|
throw new ArgumentNotProvided($this->arguments->get((string) $name)); |
85
|
|
|
} |
86
|
|
|
|
87
|
3 |
|
return $this->values->get((string) $name); |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|