1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ConsoleArgs; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Менеджер команд |
7
|
|
|
* Предоставляет возможность работы с командами через аргументы консоли |
8
|
|
|
*/ |
9
|
|
|
class Manager |
10
|
|
|
{ |
11
|
|
|
public $commands = []; |
12
|
|
|
public $defaultCommand = null; |
13
|
|
|
protected $locale; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Конструктор |
17
|
|
|
* |
18
|
|
|
* @param array $commands - список команд |
19
|
|
|
* [@param DefaultCommand $defaultCommand = null] - объект дефолтной команды |
20
|
|
|
*/ |
21
|
|
|
public function __construct (array $commands, DefaultCommand $defaultCommand = null) |
22
|
|
|
{ |
23
|
|
|
$this->locale = new Locale; |
24
|
|
|
$this->defaultCommand = $defaultCommand; |
25
|
|
|
|
26
|
|
|
foreach ($commands as $command) |
27
|
|
|
if ($command instanceof Command) |
28
|
|
|
$this->commands[$command->name] = $command; |
29
|
|
|
|
30
|
|
|
else throw new \Exception ($this->locale->command_type_exception); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* Установка локализации |
35
|
|
|
* |
36
|
|
|
* @param Locale $locale - объект локализации |
37
|
|
|
* |
38
|
|
|
* @return Manager - возвращает сам себя |
39
|
|
|
*/ |
40
|
|
|
public function setLocale (Locale $locale): Manager |
41
|
|
|
{ |
42
|
|
|
$this->locale = $locale; |
43
|
|
|
|
44
|
|
|
return $this; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Установка дефолтной команды |
49
|
|
|
* |
50
|
|
|
* @param DefaultCommand $defaultCommand - объект дефолтной команды |
51
|
|
|
* |
52
|
|
|
* @return Manager - возвращает сам себя |
53
|
|
|
*/ |
54
|
|
|
public function setDefault (DefaultCommand $defaultCommand): Manager |
55
|
|
|
{ |
56
|
|
|
$this->defaultCommand = $defaultCommand; |
57
|
|
|
|
58
|
|
|
return $this; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Итерация выполнения по аргументам |
63
|
|
|
* |
64
|
|
|
* @param array $args - список аргументов консоли |
65
|
|
|
*/ |
66
|
|
|
public function execute (array $args) |
67
|
|
|
{ |
68
|
|
|
$args = array_values ($args); |
69
|
|
|
|
70
|
|
|
if (!isset ($args[0])) |
71
|
|
|
{ |
72
|
|
|
if ($this->defaultCommand !== null) |
73
|
|
|
return $this->defaultCommand->execute ($args); |
74
|
|
|
|
75
|
|
|
else throw new \Exception ($this->locale->command_undefined_error); |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$name = $args[0]; |
79
|
|
|
$args = array_slice ($args, 1); |
80
|
|
|
|
81
|
|
|
if (!isset ($this->commands[$name])) |
82
|
|
|
{ |
83
|
|
|
foreach ($this->commands as $command) |
84
|
|
|
if (in_array ($name, $command->aliases)) |
85
|
|
|
return $command->execute ($args); |
86
|
|
|
|
87
|
|
|
return $this->defaultCommand !== null ? |
88
|
|
|
$this->defaultCommand->execute ($args) : false; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
return $this->commands[$name]->execute ($args); |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|