src/EventSubscriber/Content/ContentAddToLastViewedSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Content;
  3. use App\Service\FavoriteContentManager;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use App\Event\Content\ContentDisplayEvent;
  6. /**
  7.  * @author Marcin Skrzeszewski <marcin.skrzeszewski@avt.pl>
  8.  */
  9. class ContentAddToLastViewedSubscriber implements EventSubscriberInterface
  10. {
  11.     protected FavoriteContentManager $favoriteContentManager;
  12.     public function __construct(FavoriteContentManager $favoriteContentManager)
  13.     {
  14.         $this->favoriteContentManager $favoriteContentManager;
  15.     }
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             ContentDisplayEvent::NAME => [
  20.                 ['preContentDisplay'1000],
  21.             ]
  22.         ];
  23.     }
  24.     public function preContentDisplay(ContentDisplayEvent $event): void
  25.     {
  26.         $content $event->getContent();
  27.         $cid $content->getId();
  28.         $favs $this->favoriteContentManager->getFavoritesIds(FavoriteContentManager::KEY_LAST_VIEWED);
  29.         // Firstly check if the content is in the list
  30.         if (in_array($cid$favs)) {
  31.             // Remove the content
  32.             unset($favs[array_search($cid$favs)]);
  33.             $favs array_values($favs);
  34.         }
  35.         array_unshift($favs$cid);
  36.         // Pop out of limits elements
  37.         if (count($favs) > FavoriteContentManager::LIMIT_LAST_VIEWED)
  38.             $favs array_slice($favs0FavoriteContentManager::LIMIT_LAST_VIEWEDtrue);
  39.         $this->favoriteContentManager->replaceAllByKey($favsFavoriteContentManager::KEY_LAST_VIEWED);
  40.     }
  41. }