ApplicationTester.php 2.7 KB

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