<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WbfkExtensions\Service\AdminMailService;
class SendNotificationMailOnConsoleErrors implements EventSubscriberInterface
{
public function __construct(
private readonly AdminMailService $adminMailService,
private readonly array $commandsRequiringEmailOnError
) {
}
public static function getSubscribedEvents(): array
{
return [
ConsoleErrorEvent::class => 'onConsoleError'
];
}
public function onConsoleError(ConsoleErrorEvent $event): void
{
// If command is not in notification's list then no mailing required
if (!in_array($event->getCommand()?->getName(), $this->commandsRequiringEmailOnError)) {
return;
}
// Send error mail
$this->adminMailService->send(
'Failed command: ' . $event->getCommand()?->getName(),
$this->createPlainContent($event),
$this->createHtmlContent($event)
);
}
private function createPlainContent(ConsoleErrorEvent $event): string
{
$returnString = "Command failed: " . $event->getCommand()?->getName() . "\n\r";
if (count($event->getInput()->getArguments()) > 1) {
$arguments = $event->getInput()->getArguments();
array_shift($arguments);
$returnString .= "Command arguments: " . implode(' ', $event->getInput()->getArguments()) . "\n\r";
}
$returnString .= "Exit code: " . $event->getExitCode() . "\n\r";
$returnString .= "Error output: " . $event->getError()->getMessage() . "\n\r";
$returnString .= "Stack trace:\n\r" . $event->getError()->getTraceAsString() . "\n\r";
return $returnString;
}
private function createHtmlContent(ConsoleErrorEvent $event): string
{
$returnString = '<p>Command failed: <b>' . $event->getCommand()?->getName() . '</b></p>';
if (count($event->getInput()->getArguments()) > 1) {
$arguments = $event->getInput()->getArguments();
array_shift($arguments);
$returnString .= '<p>Command arguments: <b>' . implode(' ', $event->getInput()->getArguments()) . '</b></p>';
}
$returnString .= '<p>Exit code: <b>' . $event->getExitCode() . '</b></p>';
$returnString .= '<p>Error output: <b>' . $event->getError()->getMessage() . '</b></p>';
$returnString .= '<p>Stack trace:<br/><pre>' . $event->getError()->getTraceAsString() . '</pre></p>';
return $returnString;
}
}