<?php declare(strict_types=1);
namespace App\Subscriber;
use App\Email\ConsoleExceptionType;
use PhpAmqpLib\Exception\AMQPTimeoutException;
use Sindrive\EmailSenderBundle\Service\EmailSender;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ConsoleExceptionSubscriber implements EventSubscriberInterface
{
private EmailSender $emailSender;
public function __construct(EmailSender $emailSender)
{
$this->emailSender = $emailSender;
}
/**
* @return array<string, array<int|string, array<int|string, int|string>|int|string>|string>
*/
public static function getSubscribedEvents(): array
{
return [
ConsoleEvents::ERROR => 'onError',
ConsoleEvents::COMMAND => 'onCommand',
];
}
public function onCommand(ConsoleCommandEvent $event): void
{
// nothing - initialize EmailSender on each command before any output
}
public function onError(ConsoleErrorEvent $event): void
{
$exception = $event->getError();
$input = $event->getInput();
if ($exception instanceof AMQPTimeoutException) {
return;
}
$subject = 'Command error';
if (null !== $event->getCommand()) {
$subject = $event->getCommand()->getName() . ' ' . $subject;
}
$body = 'Input: arguments: ' . json_encode($input->getArguments(), JSON_THROW_ON_ERROR);
$body .= ' options: ' . json_encode($input->getOptions(), JSON_THROW_ON_ERROR);
$body .= '<br/>';
$body .= '<br/>';
$body .= $exception->getMessage();
$body .= '<br/>';
$body .= $exception->getFile() . ' Line: ' . $exception->getLine();
$body .= '<br/>';
$body .= '<br/>';
$body .= $exception->getTraceAsString();
$this->emailSender->sendType(new ConsoleExceptionType($subject, $body));
}
}