RunCommandMessageHandler.php 2.0 KB

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