CommandTester.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class CommandTester
  18. {
  19. private $command;
  20. private $input;
  21. private $output;
  22. /**
  23. * Constructor.
  24. *
  25. * @param Command $command A Command instance to test.
  26. */
  27. public function __construct(Command $command)
  28. {
  29. $this->command = $command;
  30. }
  31. /**
  32. * Executes the command.
  33. *
  34. * Available options:
  35. *
  36. * * interactive: Sets the input interactive flag
  37. * * decorated: Sets the output decorated flag
  38. * * verbosity: Sets the output verbosity flag
  39. *
  40. * @param array $input An array of arguments and options
  41. * @param array $options An array of options
  42. *
  43. * @return integer The command exit code
  44. */
  45. public function execute(array $input, array $options = array())
  46. {
  47. $this->input = new ArrayInput($input);
  48. if (isset($options['interactive'])) {
  49. $this->input->setInteractive($options['interactive']);
  50. }
  51. $this->output = new StreamOutput(fopen('php://memory', 'w', false));
  52. if (isset($options['decorated'])) {
  53. $this->output->setDecorated($options['decorated']);
  54. }
  55. if (isset($options['verbosity'])) {
  56. $this->output->setVerbosity($options['verbosity']);
  57. }
  58. return $this->command->run($this->input, $this->output);
  59. }
  60. /**
  61. * Gets the display returned by the last execution of the command.
  62. *
  63. * @return string The display
  64. */
  65. public function getDisplay()
  66. {
  67. rewind($this->output->getStream());
  68. return stream_get_contents($this->output->getStream());
  69. }
  70. /**
  71. * Gets the input instance used by the last execution of the command.
  72. *
  73. * @return InputInterface The current input instance
  74. */
  75. public function getInput()
  76. {
  77. return $this->input;
  78. }
  79. /**
  80. * Gets the output instance used by the last execution of the command.
  81. *
  82. * @return OutputInterface The current output instance
  83. */
  84. public function getOutput()
  85. {
  86. return $this->output;
  87. }
  88. }