vendor/kunstmaan/admin-bundle/EventListener/ToolbarListener.php line 136

Open in your IDE?
  1. <?php
  2. namespace Kunstmaan\AdminBundle\EventListener;
  3. use Kunstmaan\AdminBundle\Helper\AdminRouteHelper;
  4. use Kunstmaan\AdminBundle\Helper\Toolbar\DataCollector;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  10. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  11. use Symfony\Component\HttpKernel\HttpKernel;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  14. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  15. use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;
  16. use Symfony\Component\Security\Guard\Token\PostAuthenticationGuardToken;
  17. use Twig\Environment;
  18. class ToolbarListener implements EventSubscriberInterface
  19. {
  20.     const DISABLED 1;
  21.     const ENABLED 2;
  22.     /**
  23.      * @var Environment
  24.      */
  25.     protected $twig;
  26.     /**
  27.      * @var UrlGeneratorInterface
  28.      */
  29.     protected $urlGenerator;
  30.     /**
  31.      * @var DataCollector
  32.      */
  33.     protected $dataCollector;
  34.     /**
  35.      * @var AuthorizationChecker
  36.      */
  37.     protected $authorizationChecker;
  38.     /**
  39.      * @var TokenStorageInterface
  40.      */
  41.     protected $tokenStorage;
  42.     /**
  43.      * @var bool
  44.      */
  45.     protected $enabled;
  46.     /**
  47.      * @var ContainerInterface
  48.      */
  49.     private $container;
  50.     /**
  51.      * @var AdminRouteHelper
  52.      */
  53.     protected $adminRouteHelper;
  54.     /**
  55.      * @var array
  56.      */
  57.     protected $providerKeys;
  58.     /**
  59.      * @var array
  60.      */
  61.     protected $adminFirewallName;
  62.     /**
  63.      * ToolbarListener constructor.
  64.      *
  65.      * @param Environment           $twig
  66.      * @param UrlGeneratorInterface $urlGenerator
  67.      * @param DataCollector         $dataCollector
  68.      * @param AuthorizationChecker  $authorizationChecker
  69.      * @param TokenStorageInterface $tokenStorage
  70.      * @param bool                  $enabled
  71.      * @param ContainerInterface    $container
  72.      * @param AdminRouteHelper      $adminRouteHelper
  73.      * @param array                 $providerKeys
  74.      * @param string                $adminFirewallName
  75.      */
  76.     public function __construct(
  77.         Environment $twig,
  78.         UrlGeneratorInterface $urlGenerator,
  79.         DataCollector $dataCollector,
  80.         AuthorizationChecker $authorizationChecker,
  81.         TokenStorageInterface $tokenStorage,
  82.         $enabled,
  83.         ContainerInterface $container,
  84.         AdminRouteHelper $adminRouteHelper,
  85.         array $providerKeys,
  86.         $adminFirewallName 'main'
  87.     ) {
  88.         $this->twig $twig;
  89.         $this->urlGenerator $urlGenerator;
  90.         $this->dataCollector $dataCollector;
  91.         $this->authorizationChecker $authorizationChecker;
  92.         $this->tokenStorage $tokenStorage;
  93.         $this->enabled $enabled;
  94.         $this->container $container;
  95.         $this->adminRouteHelper $adminRouteHelper;
  96.         $this->providerKeys $providerKeys;
  97.         $this->adminFirewallName $adminFirewallName;
  98.     }
  99.     /**
  100.      * @return array
  101.      */
  102.     public static function getSubscribedEvents()
  103.     {
  104.         return [
  105.             KernelEvents::RESPONSE => ['onKernelResponse', -125],
  106.         ];
  107.     }
  108.     /**
  109.      * @return bool
  110.      */
  111.     public function isEnabled()
  112.     {
  113.         return !$this->container->has('profiler') && $this->enabled;
  114.     }
  115.     /**
  116.      * @param FilterResponseEvent|ResponseEvent $event
  117.      */
  118.     public function onKernelResponse($event)
  119.     {
  120.         if (!$event instanceof FilterResponseEvent && !$event instanceof ResponseEvent) {
  121.             throw new \InvalidArgumentException(\sprintf('Expected instance of type %s, %s given', \class_exists(ResponseEvent::class) ? ResponseEvent::class : FilterResponseEvent::class, \is_object($event) ? \get_class($event) : \gettype($event)));
  122.         }
  123.         if (!$this->isEnabled() || HttpKernel::MASTER_REQUEST !== $event->getRequestType()) {
  124.             return;
  125.         }
  126.         $response $event->getResponse();
  127.         $request $event->getRequest();
  128.         $session $request->getSession();
  129.         $url $event->getRequest()->getRequestUri();
  130.         $token $this->tokenStorage->getToken();
  131.         if (null !== $token && method_exists($token'getProviderKey')) {
  132.             $key $token->getProviderKey();
  133.         } else {
  134.             $key $this->adminFirewallName;
  135.         }
  136.         // Only enable toolbar when the kunstmaan_admin.toolbar_firewall_names config value contains the current firewall name.
  137.         if (!\in_array($key$this->providerKeysfalse)) {
  138.             return false;
  139.         }
  140.         // Only enable toolbar when we can find an authenticated user in the session from the kunstmaan_admin.admin_firewall_name config value.
  141.         $authenticated false;
  142.         /* @var PostAuthenticationGuardToken $token */
  143.         if ($session->isStarted() && $session->has(sprintf('_security_%s'$this->adminFirewallName))) {
  144.             $token unserialize($session->get(sprintf('_security_%s'$this->adminFirewallName)));
  145.             $authenticated $token->isAuthenticated();
  146.         }
  147.         // Do not capture redirects or modify XML HTTP Requests
  148.         if (!$authenticated || !$event->isMasterRequest() || $request->isXmlHttpRequest() || $this->adminRouteHelper->isAdminRoute($url)) {
  149.             return;
  150.         }
  151.         if ($response->isRedirection() || ($response->headers->has('Content-Type') && false === strpos(
  152.                     $response->headers->get('Content-Type'),
  153.                     'html'
  154.                 ))
  155.             || 'html' !== $request->getRequestFormat()
  156.             || false !== stripos($response->headers->get('Content-Disposition'), 'attachment;')
  157.         ) {
  158.             return;
  159.         }
  160.         $this->injectToolbar($response$request);
  161.     }
  162.     /**
  163.      * Injects the admin toolbar into the given Response.
  164.      *
  165.      * @param Response $response A Response instance
  166.      */
  167.     protected function injectToolbar(Response $responseRequest $request)
  168.     {
  169.         $content $response->getContent();
  170.         $pos strripos($content'</body>');
  171.         if (false !== $pos) {
  172.             $toolbar "\n".str_replace(
  173.                     "\n",
  174.                     '',
  175.                     $this->twig->render(
  176.                         '@KunstmaanAdmin/Toolbar/toolbar.html.twig',
  177.                         ['collectors' => $this->dataCollector->getDataCollectors()]
  178.                     )
  179.                 )."\n";
  180.             $content substr($content0$pos).$toolbar.substr($content$pos);
  181.             $response->setContent($content);
  182.         }
  183.     }
  184. }