CommandTester.php 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. use Symfony\Component\Console\Output\StreamOutput;
  14. /**
  15. * Eases the testing of console commands.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. * @author Robin Chalas <robin.chalas@gmail.com>
  19. */
  20. class CommandTester
  21. {
  22. use TesterTrait;
  23. private $command;
  24. private $input;
  25. private $statusCode;
  26. public function __construct(Command $command)
  27. {
  28. $this->command = $command;
  29. }
  30. /**
  31. * Executes the command.
  32. *
  33. * Available execution options:
  34. *
  35. * * interactive: Sets the input interactive flag
  36. * * decorated: Sets the output decorated flag
  37. * * verbosity: Sets the output verbosity flag
  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 = array())
  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(array('command' => $this->command->getName()), $input);
  53. }
  54. $this->input = new ArrayInput($input);
  55. if ($this->inputs) {
  56. $this->input->setStream(self::createStream($this->inputs));
  57. }
  58. if (isset($options['interactive'])) {
  59. $this->input->setInteractive($options['interactive']);
  60. }
  61. $this->output = new StreamOutput(fopen('php://memory', 'w', false));
  62. $this->output->setDecorated(isset($options['decorated']) ? $options['decorated'] : false);
  63. if (isset($options['verbosity'])) {
  64. $this->output->setVerbosity($options['verbosity']);
  65. }
  66. return $this->statusCode = $this->command->run($this->input, $this->output);
  67. }
  68. }