diff --git a/src/Application.php b/src/Application.php index 34ae4f6..b46f3f6 100644 --- a/src/Application.php +++ b/src/Application.php @@ -200,6 +200,11 @@ public function add(Command $command, string $alias = '', bool $default = false) $this->commands[$name] = $command->version($this->version)->onExit($this->onExit)->bind($this); + if (method_exists($command, "getSubCommands")) { + foreach ($command->getSubCommands() as $subcommand) { + $this->add($subcommand); + } + } return $this; } @@ -259,10 +264,26 @@ public function group(string $group, callable $fn): self public function commandFor(array $argv): Command { $argv += [null, null, null]; + $command = null; + + //sort by key length + //find maximal command compatibility by arguments + $keys = array_map('strlen', array_keys($this->commands)); + array_multisort($keys, SORT_ASC, $this->commands); + + foreach ($this->commands as $command_name => $value) { + $nb_args = count(explode(' ', $command_name)); + $args = implode(' ', array_slice($argv, 1, $nb_args)); + if (!empty($this->commands[$args])) { + $command = $this->commands[$args]; + } + } return + //cmd found by multi arguments + $command // cmd - $this->commands[$argv[1]] + ?? $this->commands[$argv[1]] // cmd alias ?? $this->commands[$this->aliases[$argv[1]] ?? null] // default. diff --git a/src/Input/Command.php b/src/Input/Command.php index bcefe31..619a015 100644 --- a/src/Input/Command.php +++ b/src/Input/Command.php @@ -450,4 +450,19 @@ protected function progress(?int $total = null): ProgressBar { return new ProgressBar($total, $this->writer()); } + + + /** + * Get all related subCommands + * + * by default is an empty array + * could be populated by any way + * Return is an array[Command] + * + * @return array Command + */ + public function getSubCommands(): Array + { + return []; + } }