CommandTester.php 2.4 KB

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