|
10 | 10 |
|
11 | 11 | use InvalidArgumentException; |
12 | 12 | use Throwable; |
| 13 | +use function array_merge; |
13 | 14 | use function array_shift; |
14 | 15 | use function array_values; |
15 | 16 | use function class_exists; |
16 | 17 | use function function_exists; |
17 | 18 | use function getcwd; |
| 19 | +use function implode; |
18 | 20 | use function is_array; |
19 | 21 | use function is_object; |
20 | 22 | use function is_string; |
@@ -120,14 +122,18 @@ public function dispatch(bool $exit = true): void |
120 | 122 | return; |
121 | 123 | } |
122 | 124 |
|
123 | | - $status = 0; |
| 125 | + if (!isset($this->commands[$command])) { |
| 126 | + $this->displayHelp("The command {$command} not exists!"); |
| 127 | + return; |
| 128 | + } |
| 129 | + |
| 130 | + if (isset($this->opts['h']) || isset($this->opts['help'])) { |
| 131 | + $this->displayCommandHelp($command); |
| 132 | + return; |
| 133 | + } |
124 | 134 |
|
125 | 135 | try { |
126 | | - if (isset($this->commands[$command])) { |
127 | | - $status = $this->runHandler($command, $this->commands[$command]); |
128 | | - } else { |
129 | | - $this->displayHelp("The command {$command} not exists!"); |
130 | | - } |
| 136 | + $status = $this->runHandler($command, $this->commands[$command]); |
131 | 137 | } catch (Throwable $e) { |
132 | 138 | $status = $this->handleException($e); |
133 | 139 | } |
@@ -230,7 +236,7 @@ public function addCommand(string $command, callable $handler, $config = null): |
230 | 236 | // save |
231 | 237 | $this->messages[$command] = $config; |
232 | 238 | } elseif (is_array($config)) { |
233 | | - $this->messages[$command] = \array_merge(self::COMMAND_CONFIG, $config); |
| 239 | + $this->messages[$command] = array_merge(self::COMMAND_CONFIG, $config); |
234 | 240 | } |
235 | 241 | } |
236 | 242 |
|
@@ -281,6 +287,31 @@ public function displayHelp(string $err = ''): void |
281 | 287 | exit(0); |
282 | 288 | } |
283 | 289 |
|
| 290 | + /** |
| 291 | + * @param string $name |
| 292 | + */ |
| 293 | + public function displayCommandHelp(string $name): void |
| 294 | + { |
| 295 | + $fullCmd = $this->script . " $name"; |
| 296 | + $config = $this->messages[$name] ?? []; |
| 297 | + $usage = "$fullCmd [args ...] [--opts ...]"; |
| 298 | + |
| 299 | + if (!$config) { |
| 300 | + $nodes = [ |
| 301 | + 'No description for the command', |
| 302 | + "<comment>Usage:</comment> \n $usage" |
| 303 | + ]; |
| 304 | + } else { |
| 305 | + $nodes = [ |
| 306 | + ucfirst($config['desc']), |
| 307 | + "<comment>Usage:</comment> \n " . ($config['usage'] ?: $usage), |
| 308 | + $config['help'] |
| 309 | + ]; |
| 310 | + } |
| 311 | + |
| 312 | + echo Color::render(implode("\n", $nodes)); |
| 313 | + } |
| 314 | + |
284 | 315 | /** |
285 | 316 | * @param string|int $name |
286 | 317 | * @param mixed $default |
|
0 commit comments