vendor/symfony/console/EventListener/ErrorListener.php line 34

Open in your IDE?
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <[email protected]>
  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\EventListener;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\Console\ConsoleEvents;
  13. use Symfony\Component\Console\Event\ConsoleErrorEvent;
  14. use Symfony\Component\Console\Event\ConsoleEvent;
  15. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  16. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  17. /**
  18. * @author James Halsall <[email protected]>
  19. * @author Robin Chalas <[email protected]>
  20. */
  21. class ErrorListener implements EventSubscriberInterface
  22. {
  23. private $logger;
  24. public function __construct(?LoggerInterface $logger = null)
  25. {
  26. $this->logger = $logger;
  27. }
  28. public function onConsoleError(ConsoleErrorEvent $event)
  29. {
  30. if (null === $this->logger) {
  31. return;
  32. }
  33. $error = $event->getError();
  34. if (!$inputString = $this->getInputString($event)) {
  35. $this->logger->critical('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]);
  36. return;
  37. }
  38. $this->logger->critical('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]);
  39. }
  40. public function onConsoleTerminate(ConsoleTerminateEvent $event)
  41. {
  42. if (null === $this->logger) {
  43. return;
  44. }
  45. $exitCode = $event->getExitCode();
  46. if (0 === $exitCode) {
  47. return;
  48. }
  49. if (!$inputString = $this->getInputString($event)) {
  50. $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]);
  51. return;
  52. }
  53. $this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]);
  54. }
  55. public static function getSubscribedEvents()
  56. {
  57. return [
  58. ConsoleEvents::ERROR => ['onConsoleError', -128],
  59. ConsoleEvents::TERMINATE => ['onConsoleTerminate', -128],
  60. ];
  61. }
  62. private static function getInputString(ConsoleEvent $event): ?string
  63. {
  64. $commandName = $event->getCommand() ? $event->getCommand()->getName() : null;
  65. $input = $event->getInput();
  66. if (method_exists($input, '__toString')) {
  67. if ($commandName) {
  68. return str_replace(["'$commandName'", "\"$commandName\""], $commandName, (string) $input);
  69. }
  70. return (string) $input;
  71. }
  72. return $commandName;
  73. }
  74. }