<?php
namespace App\EventListener;
use App\Repository\Tools\AppSettingsRepository;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
use Doctrine\ORM\EntityManagerInterface;
use App\Services\LogService;
class ErrorListener
{
private $twig;
private $appRep;
private $logService;
private $entityManager;
public function __construct(EntityManagerInterface $entityManager, Environment $twig, AppSettingsRepository $appRep, LogService $logService)
{
$this->entityManager = $entityManager;
$this->twig = $twig;
$this->appRep = $appRep;
$this->logService = $logService;
}
public function onKernelException(ExceptionEvent $event)
{
$exception = $event->getThrowable();
// dd($exception);
$statusCode = $exception instanceof HttpExceptionInterface ? $exception->getStatusCode() : 500;
$this->_getAppSettings($this->appRep);
$errorData = [
'app_settings' => $this->appSettings,
'is_error' => true,
'msg_1' => sprintf('Błąd %d', $statusCode),
'msg_2' => $this->getErrorMessage($statusCode),
'msg_3' => '',
'link' => '',
'link_name' => '',
'link_msg' => '',
];
if ($statusCode == 500) {
$logMessage = sprintf(
'%s w pliku %s w linii %d trace: %s',
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
$this->getStackTrace()
);
$this->logService->createSystemLog($logMessage);
}
$response = new Response($this->twig->render('error.html.twig', $errorData));
$event->setResponse($response);
}
private function _getAppSettings($appRepository)
{
$this->appSettings = $appRepository->getAppSettings();
}
private function getStackTrace()
{
$stackTrace = [];
$trace = debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT, 5);
foreach ($trace as $frame) {
if (isset($frame['file']) && isset($frame['line'])) {
$stackTrace[] = sprintf('%s:%d', $frame['file'], $frame['line']);
}
}
return implode("\n", $stackTrace);
}
private function getErrorMessage($statusCode)
{
switch ($statusCode) {
case 403:
return 'Brak dostępu!';
case 404:
return 'Nie znaleziono strony!';
case 500:
return 'Wystąpił błąd serwera!';
default:
return 'Wystąpił błąd serwera!';
}
}
private function handleTransaction(callable $callback)
{
try {
$this->entityManager->beginTransaction();
$callback();
$this->entityManager->commit();
} catch (\Exception $e) {
$this->entityManager->rollback();
}
}
}