bundles/Bgt/WebBundle/EventSubscriber/WebEventSubscriber.php line 37
<?php
namespace Bgt\WebBundle\EventSubscriber;
use App\Services\LanguageService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Translation\LocaleSwitcher;
use Twig\Environment;
class WebEventSubscriber implements EventSubscriberInterface
{
protected ?Environment $twigEnv;
protected LocaleSwitcher $localeSwitcher;
protected LanguageService $languageService;
public function __construct(Environment $twigEnv, LocaleSwitcher $localeSwitcher, LanguageService $languageService)
{
$this->twigEnv = $twigEnv;
$this->localeSwitcher = $localeSwitcher;
$this->languageService = $languageService;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event): void
{
$route = $event->getRequest()->get('_route');
if ($route) {
$prefix = "web_";
if (!str_starts_with($route, $prefix)) {
return;
}
}
$request = $event->getRequest();
$locale = $request->cookies->get('_locale', 'en');
if (!$this->languageService->isLangValid($locale)) {
$locale = 'en';
}
$request->setLocale($locale);
$this->localeSwitcher->setLocale($locale);
}
public function onKernelException(ExceptionEvent $event): void
{
if ($_ENV['APP_ENV'] === 'dev') {
return;
}
$route = $event->getRequest()->get('_route');
if ($route) {
$prefix = "web_";
if (!str_starts_with($route, $prefix)) {
return;
}
}
$exception = $event->getThrowable();
$response = new Response();
if ($exception instanceof NotFoundHttpException) {
$response->setStatusCode(404);
$response->setContent($this->twigEnv->render('@BgtWeb/exception/error.html.twig', [
'status' => [
'code' => 404,
'message' => "Таны хайсан мэдээлэл олдсонгүй",
],
]));
} else {
$response->setStatusCode(500);
$response->setContent($this->twigEnv->render('@BgtWeb/exception/error.html.twig', [
'status' => [
'code' => 500,
'message' => "Something is wrong contact admin",
],
]));
}
$event->setResponse($response);
}
}