RunCommandMessageHandler.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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(private readonly Application $application)
  24. {
  25. }
  26. public function __invoke(RunCommandMessage $message): RunCommandContext
  27. {
  28. $input = new StringInput($message->input);
  29. $output = new BufferedOutput();
  30. $this->application->setCatchExceptions($message->catchExceptions);
  31. try {
  32. $exitCode = $this->application->run($input, $output);
  33. } catch (UnrecoverableExceptionInterface|RecoverableExceptionInterface $e) {
  34. throw $e;
  35. } catch (\Throwable $e) {
  36. throw new RunCommandFailedException($e, new RunCommandContext($message, Command::FAILURE, $output->fetch()));
  37. }
  38. if ($message->throwOnFailure && Command::SUCCESS !== $exitCode) {
  39. throw new RunCommandFailedException(\sprintf('Command "%s" exited with code "%s".', $message->input, $exitCode), new RunCommandContext($message, $exitCode, $output->fetch()));
  40. }
  41. return new RunCommandContext($message, $exitCode, $output->fetch());
  42. }
  43. }