-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCommandDefinition.php
More file actions
109 lines (93 loc) 路 2.65 KB
/
Copy pathCommandDefinition.php
File metadata and controls
109 lines (93 loc) 路 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
declare(strict_types=1);
namespace PhpSchool\PhpWorkshop;
use PhpSchool\PhpWorkshop\Exception\InvalidArgumentException;
/**
* Represents a command in the workshop framework. Simply consists of a
* command name, required arguments and either a service name or callable to
* execute when the command is run.
*/
class CommandDefinition
{
/**
* @var string
*/
private $name;
/**
* @var array<CommandArgument>
*/
private $args = [];
/**
* @var string|callable
*/
private $commandCallable;
/**
* @param string $name The name of the command (this is how the student would invoke the command from the cli)
* @param string[]|CommandArgument[] $args A list of arguments. Must be an array of strings or `CommandArgument`'s.
* @param string|callable $commandCallable The name of a callable container entry or an actual PHP callable.
*/
public function __construct(string $name, array $args, $commandCallable)
{
$this->name = $name;
$this->commandCallable = $commandCallable;
array_walk($args, function ($arg) {
$this->addArgument($arg);
});
}
/**
* @param string|CommandArgument $argument
* @return $this
*/
public function addArgument($argument): self
{
if (!is_string($argument) && !$argument instanceof CommandArgument) {
throw InvalidArgumentException::notValidParameter(
'argument',
['string', CommandArgument::class],
$argument,
);
}
if (is_string($argument)) {
$argument = new CommandArgument($argument);
}
if (count($this->args) === 0) {
$this->args[] = $argument;
return $this;
}
$previousArgument = end($this->args);
if ($previousArgument->isOptional() && $argument->isRequired()) {
throw new InvalidArgumentException(sprintf(
'A required argument cannot follow an optional argument',
));
}
$this->args[] = $argument;
return $this;
}
/**
* Get the name of the command.
*
* @return string
*/
public function getName(): string
{
return $this->name;
}
/**
* Get the list of required arguments.
*
* @return array<CommandArgument>
*/
public function getRequiredArgs(): array
{
return $this->args;
}
/**
* Get the callable associated with this command.
*
* @return string|callable
*/
public function getCommandCallable()
{
return $this->commandCallable;
}
}