vendor/contao/core-bundle/src/EventListener/PreviewUrlCreateListener.php line 47

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * This file is part of Contao.
  5.  *
  6.  * (c) Leo Feyer
  7.  *
  8.  * @license LGPL-3.0-or-later
  9.  */
  10. namespace Contao\CoreBundle\EventListener;
  11. use Contao\ArticleModel;
  12. use Contao\CoreBundle\Event\PreviewUrlCreateEvent;
  13. use Contao\CoreBundle\Framework\ContaoFramework;
  14. use Contao\PageModel;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. /**
  17.  * @internal
  18.  */
  19. class PreviewUrlCreateListener
  20. {
  21.     /**
  22.      * @var RequestStack
  23.      */
  24.     private $requestStack;
  25.     /**
  26.      * @var ContaoFramework
  27.      */
  28.     private $framework;
  29.     public function __construct(RequestStack $requestStackContaoFramework $framework)
  30.     {
  31.         $this->requestStack $requestStack;
  32.         $this->framework $framework;
  33.     }
  34.     /**
  35.      * Adds the page ID to the front end preview URL.
  36.      *
  37.      * @throws \RuntimeException
  38.      */
  39.     public function __invoke(PreviewUrlCreateEvent $event): void
  40.     {
  41.         if (!$this->framework->isInitialized() || (!$id $event->getId()) || !\in_array($event->getKey(), ['page''article'], true)) {
  42.             return;
  43.         }
  44.         $request $this->requestStack->getCurrentRequest();
  45.         if (null === $request) {
  46.             throw new \RuntimeException('The request stack did not contain a request');
  47.         }
  48.         if ('article' === $event->getKey()) {
  49.             /** @var ArticleModel $adapter */
  50.             $adapter $this->framework->getAdapter(ArticleModel::class);
  51.             if (!$article $adapter->findByPk($id)) {
  52.                 return;
  53.             }
  54.             $id $article->pid;
  55.         }
  56.         /** @var PageModel $adapter */
  57.         $adapter $this->framework->getAdapter(PageModel::class);
  58.         if (null !== $adapter->findByPk($id)) {
  59.             $event->setQuery('page='.$id);
  60.         }
  61.     }
  62. }