<?php
namespace App\EventSubscriber\PressSite;
use App\Action\PressSite\DomainAwareAction;
use App\Action\PressSite\Localization\LandingPageAction;
use App\Service\PressSite\DomainAwareManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class DomainAwareActionSubscriber.
*/
class DomainAwareActionSubscriber implements EventSubscriberInterface
{
/**
* The helper service responsible for handling domain logic.
*
* @var \App\Service\PressSite\DomainAwareManager
*/
private $domainAwareManager;
/**
* BeforeActionSubscriber constructor.
*
* @param \App\Service\PressSite\DomainAwareManager $domainAawreManager
* The helper service responsible for handling domain logic
*/
public function __construct(DomainAwareManager $domainAawreManager)
{
$this->domainAwareManager = $domainAawreManager;
}
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
/**
* Responsible for acting as before-action event listener.
*
* This subscriber will perform any mandatory checks before
* executing given action. For instance, the mandatory
* "domain_id" query parameter can be checked here when it's
* needed for multiple actions.
*
* @param \Symfony\Component\HttpKernel\Event\ControllerEvent $event
* The instance of the dispatched event
*/
public function onKernelController(ControllerEvent $event): void
{
$controller = $event->getController();
$request = $event->getRequest();
if (!$controller instanceof DomainAwareAction) {
return;
}
// Throw exception for page not found if we cannot obtain a valid
// reference to domain entity based on the current hostname.
// Required especially for the LandingPageAction which is responsible
// for redirecting the member to sign-in page with pre-defined locale.
if (!$this->domainAwareManager->getCurrentByHostnameAndLocale()) {
$event->setController(function () {
throw new NotFoundHttpException('Page not found');
});
}
// This is a special case for the landing page and that's why we have
// separated the condition check from the one above. At first, we let
// the DomainAwareManager handle all domain entity references by
// the current hostname and language/locale requested and afterwards
// the member gets redirected to the sign-in page with the proper language
// selected. But, if we load a valid domain, but with language version
// that is not supported, then we need to thrown an exception. This case
// should be valid for all DomainAware actions, but the LandingPage.
$locale = $request->getLocale();
if (!$controller instanceof LandingPageAction && !$this->domainAwareManager->supportsLanguage($locale)) {
$event->setController(function () {
throw new NotFoundHttpException('Page not found');
});
}
}
}