vendor/symfony/maker-bundle/src/Event/ConsoleErrorSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony MakerBundle 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\Bundle\MakerBundle\Event;
  11. use Symfony\Bundle\MakerBundle\Exception\RuntimeCommandException;
  12. use Symfony\Component\Console\ConsoleEvents;
  13. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  14. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  15. use Symfony\Component\Console\Style\SymfonyStyle;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. /**
  18. * Prints certain exceptions in a pretty way and silences normal exception handling.
  19. *
  20. * @author Ryan Weaver <ryan@knpuniversity.com>
  21. */
  22. final class ConsoleErrorSubscriber implements EventSubscriberInterface
  23. {
  24. private bool $setExitCode = false;
  25. public function onConsoleError(ConsoleErrorEvent $event): void
  26. {
  27. if (!$event->getError() instanceof RuntimeCommandException) {
  28. return;
  29. }
  30. // prevent any visual logging from appearing
  31. $event->stopPropagation();
  32. // prevent the exception from actually being thrown
  33. $event->setExitCode(0);
  34. $this->setExitCode = true;
  35. $io = new SymfonyStyle($event->getInput(), $event->getOutput());
  36. $io->error($event->getError()->getMessage());
  37. }
  38. public function onConsoleTerminate(ConsoleTerminateEvent $event): void
  39. {
  40. if (!$this->setExitCode) {
  41. return;
  42. }
  43. // finally set a non-zero exit code
  44. $event->setExitCode(1);
  45. }
  46. public static function getSubscribedEvents(): array
  47. {
  48. return [
  49. ConsoleEvents::ERROR => 'onConsoleError',
  50. ConsoleEvents::TERMINATE => 'onConsoleTerminate',
  51. ];
  52. }
  53. }