RunCommandMessageHandler.php 1.5 KB

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