Skip to content

Commit

Permalink
feat: Removed dead code ExceptionViewer and redondant Logger levels…
Browse files Browse the repository at this point in the history
… constants
  • Loading branch information
ambroisemaupate committed Jul 12, 2023
1 parent f7e2a39 commit f5287f6
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 406 deletions.
1 change: 0 additions & 1 deletion lib/RoadizCompatBundle/config/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -116,5 +116,4 @@ services:
RZ\Roadiz\CompatBundle\EventSubscriber\ExceptionSubscriber:
arguments:
- '@RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface'
- '@RZ\Roadiz\CoreBundle\Exception\ExceptionViewer'
- '@service_container'
127 changes: 77 additions & 50 deletions lib/RoadizCompatBundle/src/EventSubscriber/ExceptionSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,46 @@

namespace RZ\Roadiz\CompatBundle\EventSubscriber;

use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use RZ\Roadiz\CompatBundle\Controller\AppController;
use RZ\Roadiz\CompatBundle\Theme\ThemeResolverInterface;
use RZ\Roadiz\CoreBundle\Entity\Theme;
use RZ\Roadiz\CoreBundle\Exception\ExceptionViewer;
use RZ\Roadiz\CoreBundle\Exception\MaintenanceModeException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Throwable;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;

/**
* @package RZ\Roadiz\CoreBundle\Event
*/
final class ExceptionSubscriber implements EventSubscriberInterface
{
protected LoggerInterface $logger;
protected bool $debug;
protected ExceptionViewer $viewer;
private ThemeResolverInterface $themeResolver;
private ContainerInterface $serviceLocator;
protected bool $debug;

public function __construct(
ThemeResolverInterface $themeResolver,
ExceptionViewer $viewer,
ContainerInterface $serviceLocator,
LoggerInterface $logger,
bool $debug
) {
$this->debug = $debug;
$this->viewer = $viewer;
$this->themeResolver = $themeResolver;
$this->serviceLocator = $serviceLocator;
$this->logger = $logger;
Expand All @@ -60,10 +62,70 @@ public static function getSubscribedEvents(): array
];
}

/**
* @param Request $request
* @return bool
*/
private function isFormatJson(Request $request): bool
{
if (
$request->attributes->has('_format') &&
(
$request->attributes->get('_format') == 'json' ||
$request->attributes->get('_format') == 'ld+json'
)
) {
return true;
}

$contentType = $request->headers->get('Content-Type');
if (
\is_string($contentType) &&
(
\str_starts_with($contentType, 'application/json') ||
\str_starts_with($contentType, 'application/ld+json')
)
) {
return true;
}

if (
in_array('application/json', $request->getAcceptableContentTypes()) ||
in_array('application/ld+json', $request->getAcceptableContentTypes())
) {
return true;
}

return false;
}

/**
* @param Throwable $exception
* @return int
*/
private function getHttpStatusCode(Throwable $exception): int
{
if ($exception instanceof AccessDeniedException || $exception instanceof AccessDeniedHttpException) {
return Response::HTTP_FORBIDDEN;
} elseif ($exception instanceof HttpExceptionInterface) {
return $exception->getStatusCode();
} elseif ($exception instanceof ResourceNotFoundException) {
return Response::HTTP_NOT_FOUND;
} elseif ($exception instanceof MaintenanceModeException) {
return Response::HTTP_SERVICE_UNAVAILABLE;
}

return Response::HTTP_INTERNAL_SERVER_ERROR;
}

/**
* @param ExceptionEvent $event
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws LoaderError
* @throws RuntimeError
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Throwable
* @throws SyntaxError
*/
public function onKernelException(ExceptionEvent $event): void
{
Expand All @@ -81,7 +143,7 @@ public function onKernelException(ExceptionEvent $event): void
$exception = $exception->getPrevious();
}

if (!$this->viewer->isFormatJson($event->getRequest())) {
if (!$this->isFormatJson($event->getRequest())) {
if ($exception instanceof MaintenanceModeException) {
/*
* Themed exception pages…
Expand All @@ -95,7 +157,7 @@ public function onKernelException(ExceptionEvent $event): void
/** @var Response $response */
$response = $ctrl->maintenanceAction($event->getRequest());
// Set http code according to status
$response->setStatusCode($this->viewer->getHttpStatusCode($exception));
$response->setStatusCode($this->getHttpStatusCode($exception));
$event->setResponse($response);
return;
} catch (LoaderError $error) {
Expand All @@ -109,41 +171,6 @@ public function onKernelException(ExceptionEvent $event): void
}
}

/**
* Create an emergency response to be sent instead of error logs.
*
* @param \Exception|\TypeError $e
* @param Request $request
*
* @return Response
*/
protected function getEmergencyResponse($e, Request $request): Response
{
/*
* Log error before displaying a fallback page.
*/
$class = get_class($e);
/*
* Do not flood logs with not-found errors
*/
if (!($e instanceof NotFoundHttpException) && !($e instanceof ResourceNotFoundException)) {
if ($e instanceof HttpExceptionInterface) {
// If HTTP exception do not log to critical
$this->logger->notice($e->getMessage(), [
'trace' => $e->getTraceAsString(),
'exception' => $class,
]);
} else {
$this->logger->emergency($e->getMessage(), [
'trace' => $e->getTraceAsString(),
'exception' => $class,
]);
}
}

return $this->viewer->getResponse($e, $request, $this->debug);
}

/**
* @param ExceptionEvent $event
* @return null|Theme
Expand Down Expand Up @@ -179,18 +206,18 @@ protected function isNotFoundExceptionWithTheme(ExceptionEvent $event): ?Theme

/**
* @param Theme $theme
* @param \Throwable $exception
* @param Throwable $exception
* @param ExceptionEvent $event
*
* @return Response
* @throws LoaderError
* @throws RuntimeError
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
* @throws \Throwable
* @throws \Twig\Error\SyntaxError
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Throwable
* @throws SyntaxError
*/
protected function createThemeNotFoundResponse(Theme $theme, \Throwable $exception, ExceptionEvent $event): Response
protected function createThemeNotFoundResponse(Theme $theme, Throwable $exception, ExceptionEvent $event): Response
{
$ctrlClass = $theme->getClassName();
$controller = new $ctrlClass();
Expand Down
12 changes: 1 addition & 11 deletions lib/RoadizCoreBundle/src/Entity/Log.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,6 @@
]
class Log extends AbstractEntity
{
public const EMERGENCY = Logger::EMERGENCY;
public const CRITICAL = Logger::CRITICAL;
public const ALERT = Logger::ALERT;
public const ERROR = Logger::ERROR;
public const WARNING = Logger::WARNING;
public const NOTICE = Logger::NOTICE;
public const INFO = Logger::INFO;
public const DEBUG = Logger::DEBUG;
public const LOG = Logger::INFO;

#[ORM\Column(name: 'user_id', type: 'string', length: 36, unique: false, nullable: true)]
#[SymfonySerializer\Groups(['log_user'])]
#[Serializer\Groups(['log_user'])]
Expand All @@ -61,7 +51,7 @@ class Log extends AbstractEntity
#[ORM\Column(name: 'level', type: 'integer', nullable: false)]
#[SymfonySerializer\Groups(['log'])]
#[Serializer\Groups(['log'])]
protected int $level = Log::DEBUG;
protected int $level = Logger::DEBUG;

#[ORM\Column(name: 'datetime', type: 'datetime', nullable: false)]
#[SymfonySerializer\Groups(['log'])]
Expand Down
Loading

0 comments on commit f5287f6

Please sign in to comment.