src/EventSubscriber/DeviceAwareSubscriber.php line 36

Open in your IDE?
  1. <?php
  2.     /**
  3.      * project: Pimcore - Schutzverband Nuernberg Rostbratwuerste
  4.      * User: erikb
  5.      * Year: 2022
  6.      */
  7.     namespace App\EventSubscriber;
  8.     use App\Controller\DeviceAwareController;
  9.     use Pimcore\Tool\DeviceDetector;
  10.     use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11.     use Symfony\Component\HttpKernel\Event\ControllerEvent;
  12.     use Symfony\Component\HttpKernel\Event\RequestEvent;
  13.     use Symfony\Component\HttpKernel\KernelEvents;
  14.     use Twig\Environment;
  15.     class DeviceAwareSubscriber implements EventSubscriberInterface {
  16.         protected DeviceDetector $_deviceDetector;
  17.         public function __construct(
  18.             protected Environment $twig
  19.         ) { }
  20.         public function onKernelRequest(RequestEvent $event) {
  21.             // set the variables as soon as possible, so that we're not getting troubles in
  22.             // onKernelController() if the twig environment was already initialized before
  23.             // defining global variables is only possible before the twig environment was initialized
  24.             // however you can change the value of the variable at any time later on
  25.             if ($event->isMainRequest()) {
  26.                 $this->twig->addGlobal'device'null);
  27.             }
  28.         }
  29.         public function onKernelController(ControllerEvent $event) {
  30.             $controller $event->getController();
  31.             $method null;
  32.             // when a controller class defines multiple action methods, the controller
  33.             // is returned as [$controllerInstance, 'methodName']
  34.             if (is_array($controller)) {
  35.                 $method $controller[1];
  36.                 $controller $controller[0];
  37.             }
  38.             if ($controller instanceof DeviceAwareController) {
  39.                 $this->_deviceDetector DeviceDetector::getInstance();
  40.                 $this->twig->addGlobal'device'$this->_deviceDetector->getDevice());
  41.                 $event->getRequest()->attributes->set('_device'$this->_deviceDetector->getDevice());
  42.             }
  43.         }
  44.         public static function getSubscribedEvents() {
  45.             return [
  46.                 KernelEvents::CONTROLLER => 'onKernelController',
  47.                 KernelEvents::REQUEST => ['onKernelRequest'700]
  48.             ];
  49.         }
  50.     }