RunCommandMessageHandler.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. $this->application->setCatchExceptions($message->catchExceptions);
  32. try {
  33. $exitCode = $this->application->run($input, $output);
  34. } catch (UnrecoverableExceptionInterface|RecoverableExceptionInterface $e) {
  35. throw $e;
  36. } catch (\Throwable $e) {
  37. throw new RunCommandFailedException($e, new RunCommandContext($message, Command::FAILURE, $output->fetch()));
  38. }
  39. if ($message->throwOnFailure && Command::SUCCESS !== $exitCode) {
  40. throw new RunCommandFailedException(\sprintf('Command "%s" exited with code "%s".', $message->input, $exitCode), new RunCommandContext($message, $exitCode, $output->fetch()));
  41. }
  42. return new RunCommandContext($message, $exitCode, $output->fetch());
  43. }
  44. }