CommandTester.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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;
  23. public function __construct(Command $command)
  24. {
  25. $this->command = $command;
  26. }
  27. /**
  28. * Executes the command.
  29. *
  30. * Available execution options:
  31. *
  32. * * interactive: Sets the input interactive flag
  33. * * decorated: Sets the output decorated flag
  34. * * verbosity: Sets the output verbosity flag
  35. * * capture_stderr_separately: Make output of stdOut and stdErr separately available
  36. *
  37. * @param array $input An array of command arguments and options
  38. * @param array $options An array of execution options
  39. *
  40. * @return int The command exit code
  41. */
  42. public function execute(array $input, array $options = [])
  43. {
  44. // set the command name automatically if the application requires
  45. // this argument and no command name was passed
  46. if (!isset($input['command'])
  47. && (null !== $application = $this->command->getApplication())
  48. && $application->getDefinition()->hasArgument('command')
  49. ) {
  50. $input = array_merge(['command' => $this->command->getName()], $input);
  51. }
  52. $this->input = new ArrayInput($input);
  53. // Use an in-memory input stream even if no inputs are set so that QuestionHelper::ask() does not rely on the blocking STDIN.
  54. $this->input->setStream(self::createStream($this->inputs));
  55. if (isset($options['interactive'])) {
  56. $this->input->setInteractive($options['interactive']);
  57. }
  58. if (!isset($options['decorated'])) {
  59. $options['decorated'] = false;
  60. }
  61. $this->initOutput($options);
  62. return $this->statusCode = $this->command->run($this->input, $this->output);
  63. }
  64. }