ApplicationTester.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. private $application;
  27. public function __construct(Application $application)
  28. {
  29. $this->application = $application;
  30. }
  31. /**
  32. * Executes the application.
  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. * * capture_stderr_separately: Make output of stdOut and stdErr separately available
  40. *
  41. * @return int The command exit code
  42. */
  43. public function run(array $input, array $options = [])
  44. {
  45. $prevShellVerbosity = getenv('SHELL_VERBOSITY');
  46. try {
  47. $this->input = new ArrayInput($input);
  48. if (isset($options['interactive'])) {
  49. $this->input->setInteractive($options['interactive']);
  50. }
  51. if ($this->inputs) {
  52. $this->input->setStream(self::createStream($this->inputs));
  53. }
  54. $this->initOutput($options);
  55. return $this->statusCode = $this->application->run($this->input, $this->output);
  56. } finally {
  57. // SHELL_VERBOSITY is set by Application::configureIO so we need to unset/reset it
  58. // to its previous value to avoid one test's verbosity to spread to the following tests
  59. if (false === $prevShellVerbosity) {
  60. if (\function_exists('putenv')) {
  61. @putenv('SHELL_VERBOSITY');
  62. }
  63. unset($_ENV['SHELL_VERBOSITY']);
  64. unset($_SERVER['SHELL_VERBOSITY']);
  65. } else {
  66. if (\function_exists('putenv')) {
  67. @putenv('SHELL_VERBOSITY='.$prevShellVerbosity);
  68. }
  69. $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity;
  70. $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity;
  71. }
  72. }
  73. }
  74. }