ApplicationTester.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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\Application;
  12. use Symfony\Component\Console\Input\ArrayInput;
  13. /**
  14. * Eases the testing of console applications.
  15. *
  16. * When testing an application, don't forget to disable the auto exit flag:
  17. *
  18. * $application = new Application();
  19. * $application->setAutoExit(false);
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class ApplicationTester
  24. {
  25. use TesterTrait;
  26. /**
  27. * @var \Symfony\Component\Console\Application
  28. */
  29. private $application;
  30. /**
  31. * @param \Symfony\Component\Console\Application $application
  32. */
  33. public function __construct($application)
  34. {
  35. $this->application = $application;
  36. }
  37. /**
  38. * Executes the application.
  39. *
  40. * Available options:
  41. *
  42. * * interactive: Sets the input interactive flag
  43. * * decorated: Sets the output decorated flag
  44. * * verbosity: Sets the output verbosity flag
  45. * * capture_stderr_separately: Make output of stdOut and stdErr separately available
  46. *
  47. * @return int The command exit code
  48. * @param mixed[] $input
  49. * @param mixed[] $options
  50. */
  51. public function run($input, $options = [])
  52. {
  53. $prevShellVerbosity = getenv('SHELL_VERBOSITY');
  54. try {
  55. $this->input = new ArrayInput($input);
  56. if (isset($options['interactive'])) {
  57. $this->input->setInteractive($options['interactive']);
  58. }
  59. if ($this->inputs) {
  60. $this->input->setStream(self::createStream($this->inputs));
  61. }
  62. $this->initOutput($options);
  63. return $this->statusCode = $this->application->run($this->input, $this->output);
  64. } finally {
  65. // SHELL_VERBOSITY is set by Application::configureIO so we need to unset/reset it
  66. // to its previous value to avoid one test's verbosity to spread to the following tests
  67. if (false === $prevShellVerbosity) {
  68. if (\function_exists('putenv')) {
  69. @putenv('SHELL_VERBOSITY');
  70. }
  71. unset($_ENV['SHELL_VERBOSITY']);
  72. unset($_SERVER['SHELL_VERBOSITY']);
  73. } else {
  74. if (\function_exists('putenv')) {
  75. @putenv('SHELL_VERBOSITY='.$prevShellVerbosity);
  76. }
  77. $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity;
  78. $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity;
  79. }
  80. }
  81. }
  82. }