Chris@13: Chris@13: */ Chris@13: class CommandsMatcher extends AbstractMatcher Chris@13: { Chris@13: /** @var string[] */ Chris@13: protected $commands = []; Chris@13: Chris@13: /** Chris@13: * CommandsMatcher constructor. Chris@13: * Chris@13: * @param Command[] $commands Chris@13: */ Chris@13: public function __construct(array $commands) Chris@13: { Chris@13: $this->setCommands($commands); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Set Commands for completion. Chris@13: * Chris@13: * @param Command[] $commands Chris@13: */ Chris@13: public function setCommands(array $commands) Chris@13: { Chris@13: $names = []; Chris@13: foreach ($commands as $command) { Chris@17: $names = \array_merge([$command->getName()], $names); Chris@17: $names = \array_merge($command->getAliases(), $names); Chris@13: } Chris@13: $this->commands = $names; Chris@13: } Chris@13: Chris@13: /** Chris@13: * Check whether a command $name is defined. Chris@13: * Chris@13: * @param string $name Chris@13: * Chris@13: * @return bool Chris@13: */ Chris@13: protected function isCommand($name) Chris@13: { Chris@17: return \in_array($name, $this->commands); Chris@13: } Chris@13: Chris@13: /** Chris@13: * Check whether input matches a defined command. Chris@13: * Chris@13: * @param string $name Chris@13: * Chris@13: * @return bool Chris@13: */ Chris@13: protected function matchCommand($name) Chris@13: { Chris@13: foreach ($this->commands as $cmd) { Chris@13: if ($this->startsWith($name, $cmd)) { Chris@13: return true; Chris@13: } Chris@13: } Chris@13: Chris@13: return false; Chris@13: } Chris@13: Chris@13: /** Chris@13: * {@inheritdoc} Chris@13: */ Chris@13: public function getMatches(array $tokens, array $info = []) Chris@13: { Chris@13: $input = $this->getInput($tokens); Chris@13: Chris@17: return \array_filter($this->commands, function ($command) use ($input) { Chris@13: return AbstractMatcher::startsWith($input, $command); Chris@13: }); Chris@13: } Chris@13: Chris@13: /** Chris@13: * {@inheritdoc} Chris@13: */ Chris@13: public function hasMatched(array $tokens) Chris@13: { Chris@17: /* $openTag */ \array_shift($tokens); Chris@17: $command = \array_shift($tokens); Chris@13: Chris@13: switch (true) { Chris@13: case self::tokenIs($command, self::T_STRING) && Chris@13: !$this->isCommand($command[1]) && Chris@13: $this->matchCommand($command[1]) && Chris@13: empty($tokens): Chris@13: return true; Chris@13: } Chris@13: Chris@13: return false; Chris@13: } Chris@13: }