<?php
namespace App\EventSubscriber\Content;
use App\Service\FavoriteContentManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use App\Event\Content\ContentDisplayEvent;
/**
* @author Marcin Skrzeszewski <marcin.skrzeszewski@avt.pl>
*/
class ContentAddToLastViewedSubscriber implements EventSubscriberInterface
{
protected FavoriteContentManager $favoriteContentManager;
public function __construct(FavoriteContentManager $favoriteContentManager)
{
$this->favoriteContentManager = $favoriteContentManager;
}
public static function getSubscribedEvents(): array
{
return [
ContentDisplayEvent::NAME => [
['preContentDisplay', 1000],
]
];
}
public function preContentDisplay(ContentDisplayEvent $event): void
{
$content = $event->getContent();
$cid = $content->getId();
$favs = $this->favoriteContentManager->getFavoritesIds(FavoriteContentManager::KEY_LAST_VIEWED);
// Firstly check if the content is in the list
if (in_array($cid, $favs)) {
// Remove the content
unset($favs[array_search($cid, $favs)]);
$favs = array_values($favs);
}
array_unshift($favs, $cid);
// Pop out of limits elements
if (count($favs) > FavoriteContentManager::LIMIT_LAST_VIEWED)
$favs = array_slice($favs, 0, FavoriteContentManager::LIMIT_LAST_VIEWED, true);
$this->favoriteContentManager->replaceAllByKey($favs, FavoriteContentManager::KEY_LAST_VIEWED);
}
}