RunCommandMessageHandler.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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\Messenger;
  11. use Symfony\Component\Console\Application;
  12. use Symfony\Component\Console\Command\Command;
  13. use Symfony\Component\Console\Exception\RunCommandFailedException;
  14. use Symfony\Component\Console\Input\StringInput;
  15. use Symfony\Component\Console\Output\BufferedOutput;
  16. /**
  17. * @author Kevin Bond <kevinbond@gmail.com>
  18. */
  19. final class RunCommandMessageHandler
  20. {
  21. public function __construct(
  22. private readonly Application $application,
  23. ) {
  24. }
  25. public function __invoke(RunCommandMessage $message): RunCommandContext
  26. {
  27. $input = new StringInput($message->input);
  28. $output = new BufferedOutput();
  29. $this->application->setCatchExceptions($message->catchExceptions);
  30. try {
  31. $exitCode = $this->application->run($input, $output);
  32. } catch (\Throwable $e) {
  33. throw new RunCommandFailedException($e, new RunCommandContext($message, Command::FAILURE, $output->fetch()));
  34. }
  35. if ($message->throwOnFailure && Command::SUCCESS !== $exitCode) {
  36. throw new RunCommandFailedException(sprintf('Command "%s" exited with code "%s".', $message->input, $exitCode), new RunCommandContext($message, $exitCode, $output->fetch()));
  37. }
  38. return new RunCommandContext($message, $exitCode, $output->fetch());
  39. }
  40. }