Files
KantSites/src/EventSubscriber/PublicNotFoundSubscriber.php
T
kantarci 16da844934
CMS quality / php (8.2) (push) Canceled after 0s
CMS quality / php (8.4) (push) Canceled after 0s
CMS quality / browser (push) Canceled after 0s
CMS quality / mysql (push) Canceled after 0s
feat: assign custom 404 pages with the website theme (1.8.0)
2026-09-14 12:18:33 +02:00

39 lines
1.5 KiB
PHP

<?php
namespace App\EventSubscriber;
use App\Controller\PageController;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/** Also handle human-facing unknown URLs outside the content slug grammar. */
final class PublicNotFoundSubscriber implements EventSubscriberInterface
{
public function __construct(private PageController $pages, private string $adminPath)
{
}
public static function getSubscribedEvents(): array
{
return [KernelEvents::EXCEPTION => ['onException', 10]];
}
public function onException(ExceptionEvent $event): void
{
$request = $event->getRequest();
if (!$event->isMainRequest() || !$event->getThrowable() instanceof NotFoundHttpException
|| $request->attributes->has('_route') || !in_array($request->getMethod(), ['GET', 'HEAD'], true)
|| $request->isXmlHttpRequest() || 'html' !== $request->getPreferredFormat('html')) {
return;
}
$path = $request->getPathInfo();
if (preg_match('#^/(?:'.preg_quote($this->adminPath, '#').'|media|assets|formular|install)(?:/|$)#', $path)
|| preg_match('/\.(?:css|js|mjs|json|xml|txt|png|jpe?g|webp|gif|svg|ico|woff2?|ttf|pdf)$/iD', $path)) {
return;
}
$event->setResponse($this->pages->notFound($request));
}
}