sites_group_overrides-1.x-dev/src/EventSubscriber/AjaxActiveSitesSubscriber.php
src/EventSubscriber/AjaxActiveSitesSubscriber.php
<?php
declare(strict_types=1);
namespace Drupal\sites_group_overrides\EventSubscriber;
use Drupal\sites\Event\ActiveSite;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\sites\SitePluginManagerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Subscribes on the active site event.
*/
class AjaxActiveSitesSubscriber implements EventSubscriberInterface {
/**
* Constructs a AjaxActiveSitesSubscriber object.
*
* @param \Symfony\Component\HttpFoundation\Session\SessionInterface $session
* The session.
* @param \Drupal\sites\SitePluginManagerInterface $sitePluginManager
* The site plugin manager.
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
* The Request stack.
* @param \Drupal\Core\Session\AccountInterface $currentUser
* The current user.
* @param \Drupal\Core\Access\CsrfTokenGenerator $csrfToken
* The CSRF token generator.
*/
public function __construct(
protected readonly SessionInterface $session,
protected readonly SitePluginManagerInterface $sitePluginManager,
protected readonly RequestStack $requestStack,
protected readonly AccountInterface $currentUser,
protected readonly CsrfTokenGenerator $csrfToken,
) {}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
ActiveSite::SITES_ACTIVE_SITE => ['onActiveSite', 1001],
];
}
/**
* Sets the site context if a get parameter is given.
*
* @param \Drupal\sites\Event\Sites $event
* The sites' event.
*/
public function onActiveSite(ActiveSite $event) {
if (!$csrf_token = $this->requestStack->getCurrentRequest()?->query?->get('sites_csrf')) {
return;
}
if (!$this->csrfToken->validate($csrf_token, 'sites_csrf')) {
return;
}
if ($site_id = $this->requestStack->getCurrentRequest()?->query?->get('site_id')) {
/** @var \Drupal\sites\SiteInterface $site */
$site = $this->sitePluginManager->createInstance($site_id);
$event->setActiveSite($site);
}
}
}
