ErrorListener.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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\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 <james.t.halsall@googlemail.com>
  19. * @author Robin Chalas <robin.chalas@gmail.com>
  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. return $this->logger->error('An error occurred while using the console. Message: "{message}"', ['exception' => $error, 'message' => $error->getMessage()]);
  36. }
  37. $this->logger->error('Error thrown while running command "{command}". Message: "{message}"', ['exception' => $error, 'command' => $inputString, 'message' => $error->getMessage()]);
  38. }
  39. public function onConsoleTerminate(ConsoleTerminateEvent $event)
  40. {
  41. if (null === $this->logger) {
  42. return;
  43. }
  44. $exitCode = $event->getExitCode();
  45. if (0 === $exitCode) {
  46. return;
  47. }
  48. if (!$inputString = $this->getInputString($event)) {
  49. return $this->logger->debug('The console exited with code "{code}"', ['code' => $exitCode]);
  50. }
  51. $this->logger->debug('Command "{command}" exited with code "{code}"', ['command' => $inputString, 'code' => $exitCode]);
  52. }
  53. public static function getSubscribedEvents()
  54. {
  55. return [
  56. ConsoleEvents::ERROR => ['onConsoleError', -128],
  57. ConsoleEvents::TERMINATE => ['onConsoleTerminate', -128],
  58. ];
  59. }
  60. private static function getInputString(ConsoleEvent $event)
  61. {
  62. $commandName = $event->getCommand() ? $event->getCommand()->getName() : null;
  63. $input = $event->getInput();
  64. if (method_exists($input, '__toString')) {
  65. if ($commandName) {
  66. return str_replace(["'$commandName'", "\"$commandName\""], $commandName, (string) $input);
  67. }
  68. return (string) $input;
  69. }
  70. return $commandName;
  71. }
  72. }