<?php
declare(strict_types=1);
namespace Slivki\Twig;
use Slivki\Entity\City;
use Slivki\Services\Banner\MobileFloatingBannerCacheService;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Twig\Extension\RuntimeExtensionInterface;
final class MobileFloatingBannerRuntime implements RuntimeExtensionInterface
{
private const BANNER_INDEX_SESSION_KEY = 'mobileFloatingBannerIndex';
private SessionInterface $session;
private MobileFloatingBannerCacheService $mobileFloatingBannerCacheService;
public function __construct(
SessionInterface $session,
MobileFloatingBannerCacheService $mobileFloatingBannerCacheService
) {
$this->session = $session;
$this->mobileFloatingBannerCacheService = $mobileFloatingBannerCacheService;
}
/**
* @param int[] $categories
*/
public function getMobileFloatingBanner(array $categories = []): string
{
$html = '';
$cityId = (int) $this->session->get(City::CITY_ID_SESSION_KEY, City::DEFAULT_CITY_ID);
$banners = $this->mobileFloatingBannerCacheService->getByCityAndCategories($cityId, $categories);
$bannersCount = \count($banners);
if (0 === $bannersCount) {
return $html;
}
$bannerIndex = $this->session->get(self::BANNER_INDEX_SESSION_KEY);
if (!$bannerIndex || $bannerIndex >= $bannersCount) {
$bannerIndex = 0;
}
$this->session->set(self::BANNER_INDEX_SESSION_KEY, $bannerIndex + 1);
if (isset($banners[$bannerIndex])) {
$html = $banners[$bannerIndex]->getHtml();
}
return $html;
}
}