CommandCompletionTester.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. public function __construct(
  22. private Command $command,
  23. ) {
  24. }
  25. /**
  26. * Create completion suggestions from input tokens.
  27. */
  28. public function complete(array $input): array
  29. {
  30. $currentIndex = \count($input);
  31. if ('' === end($input)) {
  32. array_pop($input);
  33. }
  34. array_unshift($input, $this->command->getName());
  35. $completionInput = CompletionInput::fromTokens($input, $currentIndex);
  36. $completionInput->bind($this->command->getDefinition());
  37. $suggestions = new CompletionSuggestions();
  38. $this->command->complete($completionInput, $suggestions);
  39. $options = [];
  40. foreach ($suggestions->getOptionSuggestions() as $option) {
  41. $options[] = '--'.$option->getName();
  42. }
  43. return array_map('strval', array_merge($options, $suggestions->getValueSuggestions()));
  44. }
  45. }