<?php
/**
* project: Pimcore - Schutzverband Nuernberg Rostbratwuerste
* User: erikb
* Year: 2022
*/
namespace App\EventSubscriber;
use App\Controller\DeviceAwareController;
use Pimcore\Tool\DeviceDetector;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;
class DeviceAwareSubscriber implements EventSubscriberInterface {
protected DeviceDetector $_deviceDetector;
public function __construct(
protected Environment $twig
) { }
public function onKernelRequest(RequestEvent $event) {
// set the variables as soon as possible, so that we're not getting troubles in
// onKernelController() if the twig environment was already initialized before
// defining global variables is only possible before the twig environment was initialized
// however you can change the value of the variable at any time later on
if ($event->isMainRequest()) {
$this->twig->addGlobal( 'device', null);
}
}
public function onKernelController(ControllerEvent $event) {
$controller = $event->getController();
$method = null;
// when a controller class defines multiple action methods, the controller
// is returned as [$controllerInstance, 'methodName']
if (is_array($controller)) {
$method = $controller[1];
$controller = $controller[0];
}
if ($controller instanceof DeviceAwareController) {
$this->_deviceDetector = DeviceDetector::getInstance();
$this->twig->addGlobal( 'device', $this->_deviceDetector->getDevice());
$event->getRequest()->attributes->set('_device', $this->_deviceDetector->getDevice());
}
}
public static function getSubscribedEvents() {
return [
KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::REQUEST => ['onKernelRequest', 700]
];
}
}