vendor/contao/news-bundle/src/EventListener/PreviewUrlCreateListener.php line 38

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\NewsBundle\EventListener;
  11. use Contao\CoreBundle\Event\PreviewUrlCreateEvent;
  12. use Contao\CoreBundle\Framework\ContaoFramework;
  13. use Contao\NewsModel;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\RequestStack;
  16. /**
  17.  * @internal
  18.  */
  19. class PreviewUrlCreateListener
  20. {
  21.     private RequestStack $requestStack;
  22.     private ContaoFramework $framework;
  23.     public function __construct(RequestStack $requestStackContaoFramework $framework)
  24.     {
  25.         $this->requestStack $requestStack;
  26.         $this->framework $framework;
  27.     }
  28.     /**
  29.      * Adds the news ID to the front end preview URL.
  30.      */
  31.     public function __invoke(PreviewUrlCreateEvent $event): void
  32.     {
  33.         if (!$this->framework->isInitialized() || 'news' !== $event->getKey()) {
  34.             return;
  35.         }
  36.         $request $this->requestStack->getCurrentRequest();
  37.         if (null === $request) {
  38.             throw new \RuntimeException('The request stack did not contain a request');
  39.         }
  40.         // Return on the news archive list page
  41.         if ('tl_news' === $request->query->get('table') && !$request->query->has('act')) {
  42.             return;
  43.         }
  44.         if ((!$id $this->getId($event$request)) || (!$newsModel $this->getNewsModel($id))) {
  45.             return;
  46.         }
  47.         $event->setQuery('news='.$newsModel->id);
  48.     }
  49.     /**
  50.      * @return int|string
  51.      */
  52.     private function getId(PreviewUrlCreateEvent $eventRequest $request)
  53.     {
  54.         // Overwrite the ID if the news settings are edited
  55.         if ('tl_news' === $request->query->get('table') && 'edit' === $request->query->get('act')) {
  56.             return $request->query->get('id');
  57.         }
  58.         return $event->getId();
  59.     }
  60.     /**
  61.      * @param int|string $id
  62.      */
  63.     private function getNewsModel($id): ?NewsModel
  64.     {
  65.         return $this->framework->getAdapter(NewsModel::class)->findByPk($id);
  66.     }
  67. }