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. public function __construct(
  27. private Application $application,
  28. ) {
  29. }
  30. /**
  31. * Executes the application.
  32. *
  33. * Available options:
  34. *
  35. * * interactive: Sets the input interactive flag
  36. * * decorated: Sets the output decorated flag
  37. * * verbosity: Sets the output verbosity flag
  38. * * capture_stderr_separately: Make output of stdOut and stdErr separately available
  39. *
  40. * @return int The command exit code
  41. */
  42. public function run(array $input, array $options = []): int
  43. {
  44. $this->input = new ArrayInput($input);
  45. if (isset($options['interactive'])) {
  46. $this->input->setInteractive($options['interactive']);
  47. }
  48. if ($this->inputs) {
  49. $this->input->setStream(self::createStream($this->inputs));
  50. }
  51. $this->initOutput($options);
  52. // Temporarily clear SHELL_VERBOSITY to prevent Application::configureIO
  53. // from overriding the interactive and verbosity settings set above
  54. $prevShellVerbosity = [getenv('SHELL_VERBOSITY'), $_ENV['SHELL_VERBOSITY'] ?? false, $_SERVER['SHELL_VERBOSITY'] ?? false];
  55. if (\function_exists('putenv')) {
  56. @putenv('SHELL_VERBOSITY');
  57. }
  58. unset($_ENV['SHELL_VERBOSITY'], $_SERVER['SHELL_VERBOSITY']);
  59. try {
  60. return $this->statusCode = $this->application->run($this->input, $this->output);
  61. } finally {
  62. if (false !== $prevShellVerbosity[0]) {
  63. if (\function_exists('putenv')) {
  64. @putenv('SHELL_VERBOSITY='.$prevShellVerbosity[0]);
  65. }
  66. }
  67. if (false !== $prevShellVerbosity[1]) {
  68. $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity[1];
  69. }
  70. if (false !== $prevShellVerbosity[2]) {
  71. $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity[2];
  72. }
  73. }
  74. }
  75. }