CommandTester.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Input\ArrayInput;
  13. /**
  14. * Eases the testing of console commands.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. * @author Robin Chalas <robin.chalas@gmail.com>
  18. */
  19. class CommandTester
  20. {
  21. use TesterTrait;
  22. private Command $command;
  23. public function __construct(
  24. callable|Command $command,
  25. ) {
  26. $this->command = $command instanceof Command ? $command : new Command(null, $command);
  27. }
  28. /**
  29. * Executes the command.
  30. *
  31. * Available execution options:
  32. *
  33. * * interactive: Sets the input interactive flag
  34. * * decorated: Sets the output decorated flag
  35. * * verbosity: Sets the output verbosity flag
  36. * * capture_stderr_separately: Make output of stdOut and stdErr separately available
  37. *
  38. * @param array $input An array of command arguments and options
  39. * @param array $options An array of execution options
  40. *
  41. * @return int The command exit code
  42. */
  43. public function execute(array $input, array $options = []): int
  44. {
  45. // set the command name automatically if the application requires
  46. // this argument and no command name was passed
  47. if (!isset($input['command'])
  48. && (null !== $application = $this->command->getApplication())
  49. && $application->getDefinition()->hasArgument('command')
  50. ) {
  51. $input = array_merge(['command' => $this->command->getName()], $input);
  52. }
  53. $this->input = new ArrayInput($input);
  54. // Use an in-memory input stream even if no inputs are set so that QuestionHelper::ask() does not rely on the blocking STDIN.
  55. $this->input->setStream(self::createStream($this->inputs));
  56. if (isset($options['interactive'])) {
  57. $this->input->setInteractive($options['interactive']);
  58. }
  59. if (!isset($options['decorated'])) {
  60. $options['decorated'] = false;
  61. }
  62. $this->initOutput($options);
  63. return $this->statusCode = $this->command->run($this->input, $this->output);
  64. }
  65. }