1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace clearice\argparser; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
class Validator |
7
|
|
|
{ |
8
|
|
|
/** |
9
|
|
|
* @param $options |
10
|
|
|
* @throws InvalidArgumentException |
11
|
|
|
*/ |
12
|
4 |
|
public function validateArguments($options, $parsed) |
13
|
|
|
{ |
14
|
4 |
|
$required = []; |
15
|
4 |
|
foreach($options as $option) { |
16
|
4 |
|
if(isset($option['required']) && $option['required'] && !isset($parsed[$option['name']]) && $option['command'] == ($parsed['__command'] ?? '')) { |
17
|
4 |
|
$required[] = $option['name']; |
18
|
|
|
} |
19
|
|
|
} |
20
|
|
|
|
21
|
4 |
|
if(!empty(($required))) { |
22
|
|
|
throw new InvalidArgumentException( |
23
|
|
|
sprintf( |
24
|
|
|
"The following options are required%s: %s. Pass the --help option for more information about possible options.", |
25
|
|
|
isset($parsed['__command']) ? " for the {$parsed['__command']} command" : "", implode(",", $required) |
26
|
|
|
) |
27
|
|
|
); |
28
|
|
|
} |
29
|
4 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @throws InvalidArgumentDescriptionException |
33
|
|
|
* @throws UnknownCommandException |
34
|
|
|
*/ |
35
|
14 |
|
public function validateOption($option, $commands) |
36
|
|
|
{ |
37
|
14 |
|
if (!isset($option['name'])) { |
38
|
1 |
|
throw new InvalidArgumentDescriptionException("Argument must have a name"); |
39
|
|
|
} |
40
|
13 |
|
if (isset($option['command']) && !isset($commands[$option['command']])) { |
41
|
1 |
|
throw new UnknownCommandException("The command {$option['command']} is unknown"); |
42
|
|
|
} |
43
|
13 |
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param $command |
47
|
|
|
* @param $commands |
48
|
|
|
* @throws CommandExistsException |
49
|
|
|
* @throws InvalidArgumentDescriptionException |
50
|
|
|
*/ |
51
|
5 |
|
public function validateCommand($command, $commands) |
52
|
|
|
{ |
53
|
5 |
|
if (!isset($command['name'])) { |
54
|
1 |
|
throw new InvalidArgumentDescriptionException("Command description must contain a name"); |
55
|
|
|
} |
56
|
5 |
|
if (isset($commands[$command['name']])) { |
57
|
1 |
|
throw new CommandExistsException("Command ${command['name']} already exists."); |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
} |