CommandCompletionTester.php 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Tester;
  11. use Symfony\Component\Console\Command\Command;
  12. use Symfony\Component\Console\Completion\CompletionInput;
  13. use Symfony\Component\Console\Completion\CompletionSuggestions;
  14. /**
  15. * Eases the testing of command completion.
  16. *
  17. * @author Jérôme Tamarelle <jerome@tamarelle.net>
  18. */
  19. class CommandCompletionTester
  20. {
  21. private $command;
  22. public function __construct(Command $command)
  23. {
  24. $this->command = $command;
  25. }
  26. /**
  27. * Create completion suggestions from input tokens.
  28. */
  29. public function complete(array $input): array
  30. {
  31. $currentIndex = \count($input);
  32. if ('' === end($input)) {
  33. array_pop($input);
  34. }
  35. array_unshift($input, $this->command->getName());
  36. $completionInput = CompletionInput::fromTokens($input, $currentIndex);
  37. $completionInput->bind($this->command->getDefinition());
  38. $suggestions = new CompletionSuggestions();
  39. $this->command->complete($completionInput, $suggestions);
  40. $options = [];
  41. foreach ($suggestions->getOptionSuggestions() as $option) {
  42. $options[] = '--'.$option->getName();
  43. }
  44. return array_map('strval', array_merge($options, $suggestions->getValueSuggestions()));
  45. }
  46. }