39 lines
1.5 KiB
PHP
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));
|
|
}
|
|
}
|