- <?php
- namespace Slivki\Twig;
- use DateTimeInterface;
- use Doctrine\ORM\EntityManagerInterface;
- use IntlDateFormatter;
- use Slivki\Controller\SiteController;
- use Slivki\Dao\OfferCode\PurchaseCountDaoInterface;
- use Slivki\Entity\BankCurrency;
- use Slivki\Entity\BrandingBanner;
- use Slivki\Entity\Category;
- use Slivki\Entity\CategoryType;
- use Slivki\Entity\City;
- use Slivki\Entity\Comment;
- use Slivki\Entity\Director;
- use Slivki\Entity\InfoPage;
- use Slivki\Entity\MailingCampaign;
- use Slivki\Entity\Media;
- use Slivki\Entity\Media\OfferSupplierPhotoMedia;
- use Slivki\Entity\MediaType;
- use Slivki\Entity\NoticePopup;
- use Slivki\Entity\NoticePopupView;
- use Slivki\Entity\Offer;
- use Slivki\Entity\OfferExtensionVariant;
- use Slivki\Entity\PriceDeliveryType;
- use Slivki\Entity\ProductCategory;
- use Slivki\Entity\ProductFastDelivery;
- use Slivki\Entity\PurchaseCount;
- use Slivki\Entity\Sale;
- use Slivki\Entity\Seo;
- use Slivki\Entity\SiteSettings;
- use Slivki\Entity\UserGroup;
- use Slivki\Entity\Visit;
- use Slivki\Entity\VisitCounter;
- use Slivki\Enum\SwitcherFeatures;
- use Slivki\Repository\OfferRepository;
- use Slivki\Repository\ProductFastDeliveryRepository;
- use Slivki\Repository\SeoRepository;
- use Slivki\Services\BannerService;
- use Slivki\Services\CacheService;
- use Slivki\Services\ImageService;
- use Slivki\Services\RTBHouseService;
- use Slivki\Services\Sidebar\SidebarCacheService;
- use Slivki\Services\Switcher\ServerFeatureStateChecker;
- use Slivki\Services\TextCacheService;
- use Slivki\Twig\Filter\PhoneNumberFilterTwigRuntime;
- use Slivki\Twig\Filter\ShortPriceFilterTwigRuntime;
- use Slivki\Util\OAuth2Client\AbstractOAuth2Client;
- use Slivki\Util\SoftCache;
- use Slivki\Util\CommonUtil;
- use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
- use Symfony\Component\HttpFoundation\RequestStack;
- use Slivki\Entity\User;
- use Slivki\Util\Logger;
- use Symfony\Component\DomCrawler\Crawler;
- use Symfony\Component\HttpFoundation\Session\Session;
- use Slivki\Repository\SiteSettingsRepository;
- use Symfony\Component\HttpKernel\KernelInterface;
- use Symfony\Component\Security\Acl\Exception\Exception;
- use Twig\Environment;
- use Twig\Extension\AbstractExtension;
- use Twig\TwigFilter;
- use Twig\TwigFunction;
- use Twig\TwigTest;
- class SlivkiTwigExtension extends AbstractExtension {
-     private $partnerLogoURL = null;
-     private $entityManager;
-     private $request;
-     private $imageService;
-     private $bannerService;
-     private $textCacheService;
-     private $kernel;
-     private $cacheService;
-     private $RTBHouseService;
-     private static $photoGuideMenuItem = null;
-     private SidebarCacheService $sidebarCacheService;
-     private ServerFeatureStateChecker $serverFeatureStateChecker;
-     private ParameterBagInterface $parameterBag;
-     private PurchaseCountDaoInterface $purchaseCountDao;
-     public function __construct(
-         EntityManagerInterface $entityManager,
-         RequestStack $requestStack,
-         ImageService $imageService,
-         BannerService $bannerService,
-         TextCacheService $textCacheService,
-         KernelInterface $kernel,
-         CacheService $cacheService,
-         RTBHouseService $RTBHouseService,
-         SidebarCacheService $sidebarCacheService,
-         ServerFeatureStateChecker $serverFeatureStateChecker,
-         ParameterBagInterface $parameterBag,
-         PurchaseCountDaoInterface $purchaseCountDao
-     ) {
-         $this->entityManager = $entityManager;
-         $this->request = $requestStack->getMainRequest();
-         $this->imageService = $imageService;
-         $this->bannerService = $bannerService;
-         $this->textCacheService = $textCacheService;
-         $this->kernel = $kernel;
-         $this->cacheService = $cacheService;
-         $this->RTBHouseService = $RTBHouseService;
-         $this->sidebarCacheService = $sidebarCacheService;
-         $this->serverFeatureStateChecker = $serverFeatureStateChecker;
-         $this->parameterBag = $parameterBag;
-         $this->purchaseCountDao = $purchaseCountDao;
-     }
-     public function getFilters(): array
-     {
-         return [
-             new TwigFilter('plural', [$this, 'pluralFilter']),
-             new TwigFilter('preg_replace', [$this, 'pregReplaceFilter']),
-             new TwigFilter('localizedate', [$this, 'localizeDateFilter']),
-             new TwigFilter('localize_timestamp_date', [$this, 'localizeDateTimestampFilter']),
-             new TwigFilter('phone', [$this, 'phoneFilter']),
-             new TwigFilter('json_decode', [$this, 'jsonDecodeFilter']),
-             new TwigFilter('short_price', [ShortPriceFilterTwigRuntime::class, 'shortPriceFormat']),
-             new TwigFilter('phone_number', [PhoneNumberFilterTwigRuntime::class, 'phoneNumberFormat']),
-         ];
-     }
-     public function getFunctions() {
-         return array(
-             new TwigFunction("getTopLevelCategories", array($this, "getTopLevelCategories")),
-             new TwigFunction("getMetaInfo", array($this, "getMetaInfo")),
-             new TwigFunction("getURL", array($this, "getURL")),
-             new TwigFunction("getCategoryURL", array($this, "getCategoryURL")),
-             new TwigFunction("getCategoriesList", array($this, "getCategoriesList")),
-             new TwigFunction("getCityList", array($this, "getCityList")),
-             new TwigFunction("getTopCityList", array($this, "getTopCityList")),
-             new TwigFunction("getCategoryTypeList", array($this, "getCategoryTypeList")),
-             new TwigFunction("getImageURL", array($this, "getImageURL")),
-             new TwigFunction("getSidebar", [$this, "getSidebar"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getProfileImageURL", [$this, "getProfileImageURL"]),
-             new TwigFunction("getSiteSettings", [$this, "getSiteSettings"]),
-             new TwigFunction("staticCall", [$this, "staticCall"]),
-             new TwigFunction("getVisitCount",[$this, "getVisitCount"]),
-             new TwigFunction("getOfferVisitCount",[$this, "getOfferVisitCount"]),
-             new TwigFunction("getSaleVisitCount",[$this, "getSaleVisitCount"]),
-             new TwigFunction("getVideoGuideVisitCount",[$this, "getVideoGuideVisitCount"]),
-             new TwigFunction("getOfferMonthlyPurchaseCount",[$this, "getOfferMonthlyPurchaseCount"]),
-             new TwigFunction("getTopSiteBanner",[$this, "getTopSiteBanner"], ['is_safe' => ['html'], 'needs_environment' => false]),
-             new TwigFunction("getCategoryBanner",[$this, "getCategoryBanner"]),
-             new TwigFunction('getCommentsBanners',[GetCommentsBanners::class, 'getCommentsBanners']),
-             new TwigFunction("getGoogleBanner",[$this, "getGoogleBanner"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getBankCurrencyList", array($this, "getBankCurrencyList")),
-             new TwigFunction("getCategoryBreadcrumbs", array($this, "getCategoryBreadcrumbs")),
-             new TwigFunction("getLastComments", [$this, "getLastComments"]),
-             new TwigFunction("getCommentEntityByType", [$this, "getCommentEntityByType"]),
-             new TwigFunction("getCommentsMenuItems", [$this, "getCommentsMenuItems"]),
-             new TwigFunction("getMainMenu", [$this, "getMainMenu"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getActiveSubCategories", [$this, "getActiveSubCategories"]),
-             new TwigFunction("getActiveSalesCount", [$this, "getActiveSalesCount"]),
-             new TwigFunction("getActiveOffersCount", [$this, "getActiveOffersCount"]),
-             new TwigFunction("getPartnerLogoURL", [$this, "getPartnerLogoURL"]),
-             new TwigFunction("getCommentsCountByUserID", [$this, "getCommentsCountByUserID"]),
-             new TwigFunction("getInfoPages", [$this, "getInfoPages"]),
-             new TwigFunction("getSaleShortDescription", [$this, "getSaleShortDescription"]),
-             new TwigFunction("isMobileDevice", [$this, "isMobileDevice"]),
-             new TwigFunction("getNoticePopup", [$this, "getNoticePopup"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getBrandingBanner", [$this, "getBrandingBanner"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("addSchemeAndHttpHostToImageSrc", [$this, "addSchemeAndHttpHostToImageSrc"]),
-             new TwigFunction("getSupplierOfferPhotoBlockByOfferID", [$this, "getSupplierOfferPhotoBlockByOfferID"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getUserCommentsMediaBlockByEntityID", [$this, "getUserCommentsMediaBlockByEntityID"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getEntityRatingWithCount", [$this, "getEntityRatingWithCount"]),
-             new TwigFunction("getInfoLine", [$this, "getInfoLine"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getTeaserWatermark", [$this, "getTeaserWatermark"]),
-             new TwigFunction("getCompaniesRatingBlock", [$this, "getCompaniesRatingBlock"], ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getTestMenuItem", [$this, "getTestMenuItem"]),
-             new TwigFunction("getMailingCampaignEntityPositionByEntityID", [$this, "getMailingCampaignEntityPositionByEntityID"]),
-             new TwigFunction("getUsersOnlineCount", [$this, "getUsersOnlineCount"]),
-             new TwigFunction("getActiveCityList", [$this, "getActiveCityList"]),
-             new TwigFunction("getActiveSortedCityList", [$this, "getActiveSortedCityList"]),
-             new TwigFunction("getCurrentCity", [$this, "getCurrentCity"]),
-             new TwigFunction("setSeenMicrophoneTooltip", [$this, "setSeenMicrophoneTooltip"]),
-             new TwigFunction("getFlierProductCategories", [$this, "getFlierProductCategories"],  ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getFlierProductSubCategories", [$this, "getFlierProductSubCategories"],  ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("getIPLocationData", [$this, "getIPLocationData"]),
-             new TwigFunction("isInDefaultCity", [$this, "isInDefaultCity"]),
-             new TwigFunction("showMyPromocodesMenuItem", [$this, "showMyPromocodesMenuItem"]),
-             new TwigFunction("getFooter", [$this, "getFooter"],  ['is_safe' => ['html'], 'needs_environment' => true]),
-             new TwigFunction("addLazyAndLightboxImagesInDescription", [$this, "addLazyAndLightboxImagesInDescription"]),
-             new TwigFunction("getStatVisitCount", [$this, "getStatVisitCount"]),
-             new TwigFunction("getSaleCategoriesSortedBySaleVisits", [$this, "getSaleCategoriesSortedBySaleVisits"]),
-             new TwigFunction("getMedia", [$this, "getMedia"]),
-             new TwigFunction("logWrite", [$this, "logWrite"]),
-             new TwigFunction('getLastVisitedOffersByUserId', [GetLastVisitedOffersTwigRuntime::class, 'getLastVisitedOffersByUserId']),
-             new TwigFunction("getManagerPhoneNumber", [$this, "getManagerPhoneNumber"]),
-             new TwigFunction("getSocialProviderLoginUrl", [$this, "getSocialProviderLoginUrl"]),
-             new TwigFunction("getBannerCodeFromFile", [$this, "getBannerCodeFromFile"]),
-             new TwigFunction("getCurrentCityURL", [$this, "getCurrentCityURL"]),
-             new TwigFunction("getMobileFloatingBanner", [MobileFloatingBannerRuntime::class, "getMobileFloatingBanner"]),
-             new TwigFunction("isTireDirector", [$this, "isTireDirector"]),
-             new TwigFunction('isProductFastDelivery', [$this, 'isProductFastDelivery']),
-             new TwigFunction('calcDeliveryPriceOffer', [$this, 'calcDeliveryPriceOffer']),
-             new TwigFunction('calcDishDiscount', [$this, 'calcDishDiscount']),
-             new TwigFunction('getRTBHouseUID', [$this, 'getRTBHouseUID']),
-             new TwigFunction('getOfferConversion', [$this, 'getOfferConversion']),
-             new TwigFunction('getVimeoEmbedPreview', [$this, 'getVimeoEmbedPreview']),
-             new TwigFunction('qrGeneratorMessage', [QRMessageGeneratorRuntime::class, 'qrGeneratorMessage']),
-             new TwigFunction('getFilterOrdersCount', [OnlineOrderHistoryTwigRuntime::class, 'getFilterOrdersCount']),
-             new TwigFunction('getUserBalanceCodesCount', [$this, 'getUserBalanceCodesCount']),
-             new TwigFunction('showAppInviteModal', [$this, 'showAppInviteModal']),
-             new TwigFunction('getOfferManagers', [UserGroupTwigRuntime::class, 'getOfferManagers']),
-             new TwigFunction('getLinkOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkOnlineOrder']),
-             new TwigFunction('getLinkFoodOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkFoodOnlineOrder']),
-             new TwigFunction('getLinkGiftCertificateOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkGiftCertificateOnlineOrder']),
-             new TwigFunction('getLinkGiftCertificateOnlineOrderByOnlyCode', [GetLinkOnlineOrderRuntime::class, 'getLinkGiftCertificateOnlineOrderByOnlyCode']),
-             new TwigFunction('getLinkTireOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkTireOnlineOrder']),
-             new TwigFunction('isSubscriber', [SubscriptionTwigRuntime::class, 'isSubscriber']),
-             new TwigFunction('getSubscription', [SubscriptionTwigRuntime::class, 'getSubscription']),
-             new TwigFunction('getOfferCommentsCount', [GetCommentsCountTwigRuntime::class, 'getOfferCommentsCount']),
-             new TwigFunction('getDeliveryTimeText', [DeliveryTimeTextTwigRuntime::class, 'getDeliveryTimeText']),
-             new TwigFunction('getCertificateAddresses', [GiftCertificateTwigRuntime::class, 'getCertificateAddresses']),
-             new TwigFunction('isServerFeatureEnabled', [ServerFeatureStateTwigRuntime::class, 'isServerFeatureEnabled']),
-             new TwigFunction('getDishNutrients', [GetDishNutrientsTwigRuntime::class, 'getDishNutrients']),
-             new TwigFunction('getUserAverageCommentRating', [GetUserAverageCommentRatingTwigRuntime::class, 'getUserAverageCommentRating']),
-             new TwigFunction('getGiftSubscription', [GiftSubscriptionRuntime::class, 'getSubscription']),
-             new TwigFunction('getVoiceMessage', [VoiceMessageTwigRuntime::class, 'getVoiceMessage']),
-             new TwigFunction('getPhoneOrEmailForActivity', [UserInfoForTransferActivityTwigRuntime::class, 'getPhoneOrEmailForActivity'])
-         );
-     }
-     public function getTests() {
-         return [
-             new TwigTest('instanceof', [$this, 'isInstanceof']),
-             new TwigTest('object', [$this, 'isObject'])
-         ];
-     }
-     public function getTeaserWatermark($offerID) {
-         return $this->entityManager->getRepository(Offer::class)->getTeaserWatermark($offerID);
-     }
-     public function addSchemeAndHttpHostToImageSrc($text) {
-         $schemeAndHttpHost = $this->request->getSchemeAndHttpHost();
-         return preg_replace('/(<img.*src=")(?!http)[\/]{0,1}([^"]*)/', "$1".$schemeAndHttpHost."/$2", $text);
-     }
-     public function getBrandingBanner(Environment $twig, $user, $categoryIDs = [], $offerID = null) {
-         // TODO:: REFACTORING AND CACHING
-         $brandingBannerList = [];
-         if ($user && $user->getEmail() == 'kristina@slivki.by') {
-             $dql = "select brandingBanner from Slivki:BrandingBanner brandingBanner where brandingBanner.test = :test order by brandingBanner.ID desc";
-             $brandingBannerList = $this->entityManager->createQuery($dql)->setParameter('test', true)->getResult();
-         }
-         if (empty($brandingBannerList)) {
-             $dql = "select brandingBanner from Slivki:BrandingBanner brandingBanner where brandingBanner.activeSince < :timeFrom and brandingBanner.activeTill > :timeTo and brandingBanner.test = :test and brandingBanner.active = :active order by brandingBanner.ID desc";
-             $brandingBannerList = $this->entityManager->createQuery($dql)
-                 ->setParameter('timeFrom', new \DateTime())
-                 ->setParameter('timeTo', (new \DateTime())->modify('-1 day'))
-                 ->setParameter('test', false)->setParameter('active', true)
-                 ->getResult();
-             $bannersForCity = [];
-             $currentCityID = (int) $this->getCurrentCity()->getID();
-             foreach ($brandingBannerList as $key => $item) {
-                 if (in_array($currentCityID, $item->getCityIds(), true)) {
-                     $bannersForCity[] = $item;
-                 } else {
-                     unset($brandingBannerList[$key]);
-                 }
-             }
-             if (!empty($bannersForCity)) {
-                 $brandingBannerList = $bannersForCity;
-             }
-         }
-         $currentBrandingBanner = [];
-         $refreshCookie = $this->request->cookies->get('refresh');
-         if (empty($categoryIDs) && strpos($this->request->headers->get('referer'), 'https://www.t.dev.slivki.by') === false && !$refreshCookie) {
-             foreach ($brandingBannerList as $branding) {
-                 if ($branding->getTitle() == 'yandex') {
-                     $currentBrandingBanner = [$branding];
-                 }
-             }
-         }
-         if (!$currentBrandingBanner) {
-             $breaker = false;
-             $currentCategory = null;
-             $categoryBrandingBannerList = [];
-             /** @var  BrandingBanner $item */
-             foreach ($categoryIDs as $categoryID) {
-                 $currentCategory = $this->entityManager->getRepository(Category::class)->find($categoryID);
-                 if ($currentCategory) {
-                     /** @var BrandingBanner $brandingBanner */
-                     foreach ($brandingBannerList as $item) {
-                         if ($item->isPassThrough()) {
-                             $categoryBrandingBannerList[] = $item;
-                         } else if ($item->isForCategories()) {
-                             foreach ($item->getCategories() as $brandingBannerCategory) {
-                                 if ($brandingBannerCategory->getID() == $categoryID || $currentCategory->isChildOfRecursive($brandingBannerCategory->getID())) {
-                                     $categoryBrandingBannerList[] = $item;
-                                     break;
-                                 }
-                             }
-                         }
-                     }
-                 }
-             }
-             if (!empty($categoryBrandingBannerList)) {
-                 $brandingBannerList = $categoryBrandingBannerList;
-             } else {
-                 foreach ($categoryIDs as $categoryID) {
-                     $currentCategory = $this->entityManager->getRepository(Category::class)->find($categoryID);
-                     if ($currentCategory) {
-                         foreach ($brandingBannerList as $key=>$item) {
-                             $removeCategoryFlag = true;
-                             if ($item->isForCategories() && !$item->isPassThrough()) {
-                                 foreach ($item->getCategories() as $brandingBannerCategory) {
-                                     if (in_array($brandingBannerCategory->getID(), $categoryIDs) || $currentCategory->isChildOfRecursive($brandingBannerCategory->getID())) {
-                                         $removeCategoryFlag = false;
-                                         break;
-                                     }
-                                 }
-                                 if ($removeCategoryFlag) {
-                                     unset($brandingBannerList[$key]);
-                                 }
-                             }
-                         }
-                     }
-                 }
-                 if (empty($categoryIDs)) {
-                     foreach ($brandingBannerList as $key=>$item) {
-                         if ($item->isForCategories() && !$item->isPassThrough()) {
-                             unset($brandingBannerList[$key]);
-                         }
-                     }
-                 }
-             }
-             $brandingBannerList = array_values(array_unique($brandingBannerList, SORT_REGULAR));
-             if (!$this->isMobileDevice()) {
-                 foreach ($brandingBannerList as $brandingBanner) {
-                     if (empty($currentBrandingBanner) or $breaker == true) {
-                         $currentBrandingBanner = $brandingBanner;
-                     }
-                     if ($breaker) {
-                         break;
-                     }
-                     if ($brandingBanner->getBannerID() == $this->request->cookies->get('fullSiteBanner1')) {
-                         $breaker = true;
-                     }
-                 }
-             } else {
-                 foreach ($brandingBannerList as $brandingBanner) {
-                     if (($brandingBanner->getMobileImage() || $brandingBanner->getMobileDivider()) && (empty($currentBrandingBanner) || $breaker == true)) {
-                         $currentBrandingBanner = $brandingBanner;
-                     }
-                     if ($breaker) {
-                         break;
-                     }
-                     if ($brandingBanner->getBannerID() == $this->request->cookies->get('fullSiteBanner1')) {
-                         $breaker = true;
-                     }
-                 }
-             }
-         }
-         if (self::isMobileDevice()) {
-             return empty($currentBrandingBanner) ? null : $currentBrandingBanner;
-         }
-         if (empty($currentBrandingBanner)) {
-             return '';
-         } else {
-             if (is_array($currentBrandingBanner)) {
-                 $currentBrandingBanner = $currentBrandingBanner[0];
-             }
-             return $twig->render('Slivki/banners/branding_banner.html.twig', ['brandingBanner' => $currentBrandingBanner]);
-         }
-     }
-     public function getNoticePopup(Environment $twig, $user) {
-         $noticePopup = '';
-         $directorPopupID = null;
-         try {
-             /** @var User $user */
-             if (($user && $user->hasRole(UserGroup::ROLE_SUPPLIER_ID))) {
-                 if (!$user->hasRole(UserGroup::ROLE_DIRECTOR_A) && !$user->hasRole(UserGroup::ROLE_DIRECTOR_B)) {
-                     $softCache = new SoftCache('director');
-                     $lastDirectorGroup = $softCache->get('last_director_group', 0);
-                     $lastDirectorGroup++;
-                     if ($lastDirectorGroup > 1) {
-                         $lastDirectorGroup = 0;
-                     }
-                     $softCache->set('last_director_group', $lastDirectorGroup, 0);
-                     if ($lastDirectorGroup == 0) {
-                         $role = $this->entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_DIRECTOR_A);
-                         $user->addRole($role);
-                     } else {
-                         $role = $this->entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_DIRECTOR_B);
-                         $user->addRole($role);
-                     }
-                     $this->entityManager->flush();
-                 }
-                 if ($user->hasRole(UserGroup::ROLE_DIRECTOR_A)) {
-                     $directorPopupID = NoticePopup::ID_DIRECTOR_A;
-                 } else {
-                     $directorPopupID = NoticePopup::ID_DIRECTOR_B;
-                 }
-                 $noticePopup = $this->getNoticePopupByID($twig, $user, $directorPopupID);
-             }
-             if ($noticePopup == '') {
-                 $noticePopup = $this->getNoticePopupByID($twig, $user, NoticePopup::ID_USER);
-             }
-             if ($user && $user->getEmail() == 'volga@slivki.by') {
-                 $testPopups = $this->entityManager->getRepository(NoticePopup::class)->findBy(['test' => true, 'type' => $directorPopupID]);
-                 if (isset($testPopups[0])) {
-                     $noticePopup = $this->getNoticePopupByID($twig, $user, $testPopups[0]->getType());
-                 }
-             }
-         } catch (\Exception $e) {
-             Logger::instance('Notice popup error')->info($e->getMessage());
-             return '';
-         }
-         return $noticePopup;
-     }
-     private function getNoticePopupByID(Environment $twig, $user, $type) {
-         if ($this->isMobileDevice()) {
-             return '';
-         }
-         $dql = 'select noticePopup from Slivki:NoticePopup noticePopup where noticePopup.active = true and noticePopup.type = :type and current_timestamp() between noticePopup.activeFrom and noticePopup.activeTill';
-         $noticePopupList = $this->entityManager->createQuery($dql)->setParameter('type', $type)->getResult();
-         if (!$noticePopupList || count($noticePopupList) == 0) {
-             return '';
-         }
-         $noticePopup = $noticePopupList[0];
-         if ($noticePopup->isTest() && $user && $user->getEmail() == 'volga@slivki.by') {
-             $noticePopupHtml = $this->getNoticePopupHtmlView($twig, $noticePopup);
-             return $noticePopupHtml == SoftCache::EMPTY_VALUE ? '' : $noticePopupHtml;
-         }
-         if ($noticePopup) {
-             if ($this->isNoticePopupShown($noticePopup->getCookieName(), $user, $noticePopup->getID())) {
-                 return '';
-             }
-         }
-         $noticePopupHtml = $this->getNoticePopupHtmlView($twig, $noticePopup);
-         return $noticePopupHtml == SoftCache::EMPTY_VALUE ? '' : $noticePopupHtml;
-     }
-     private function getNoticePopupHtmlView(Environment $twig, $noticePopup) {
-         $noticePopupID = $noticePopup->getID();
-         $image = $this->entityManager->getRepository(Media::class)
-             ->findOneBy(['entityID' => $noticePopupID, 'mediaType' => MediaType::TYPE_NOTICE_POPUP_IMAGE_ID], ['ID' => 'desc']);
-         $imageMobile = $this->entityManager->getRepository(Media::class)
-             ->findOneBy(['entityID' => $noticePopupID, 'mediaType' => MediaType::TYPE_NOTICE_POPUP_IMAGE_ID_MOBILE], ['ID' => 'desc']);
-         return $twig->render('Slivki/popups/notice_popup.html.twig',
-             ['id'=> 'notice_popup', 'noticePopup' => $noticePopup, 'image' => $image, 'imageMobile' => $imageMobile]);
-     }
-     private function isNoticePopupShown($popupID, $user, $sessionKeySuffix) {
-         if (!$user) {
-             return false;
-         }
-         $session = new Session();
-         $sessionKey = 'noticePopup' . $sessionKeySuffix;
-         $noticePopupID = $session->get($sessionKey);
-         if (!$noticePopupID) {
-             $popupView = $this->entityManager->getRepository(NoticePopupView::class)->findBy(['popupID' => $popupID, 'userID' => $user->getID()]);
-             if (!$popupView) {
-                 $popupView = new NoticePopupView();
-                 $popupView->setCreatedOn(new \DateTime());
-                 $popupView->setPopupID($popupID);
-                 $popupView->setUserID($user->getID());
-                 $this->entityManager->persist($popupView);
-                 $this->entityManager->flush($popupView);
-                 return false;
-             }
-             $session->set($sessionKey, $popupID);
-             return true;
-         }
-         if ($noticePopupID != $popupID) {
-             $session->set($sessionKey, $popupID);
-             return false;
-         }
-         return true;
-     }
-     public function isMobileDevice() {
-         return CommonUtil::isMobileDevice($this->request);
-     }
-     public function getInfoPages($type) {
-         return $this->entityManager->getRepository(InfoPage::class)->getInfoPagesFromCache($type);
-     }
-     public function getTopSiteBanner($categoryIDs = [], $mobile, $mobileCache = false) {
-         return $this->bannerService->getHeadBannerCached($this->getCurrentCity()->getID(), $categoryIDs, $mobile, $mobileCache);
-     }
-     public function getCategoryBanner($categoryID) {
-         $categoryRepository = $this->entityManager->getRepository(Category::class);
-         $category = $categoryRepository->findCached($categoryID);
-         if (isset($category['category']) && $category['category'] instanceof Category) {
-             return $this->bannerService->getCategoryBannerCached($category['category'], self::isMobileDevice());
-         }
-         return '';
-     }
-     public function getGoogleBanner(Environment $twig) {
-         return $twig->render('Slivki/banners/head_banner_admixer.html.twig');
-     }
-     public function getCategoryTypeList() {
-         return $this->entityManager->getRepository(CategoryType::class)->findAll();
-     }
-     public function getLastComments() {
-         $dql = 'select comment from Slivki:Comment comment where comment.hidden = false and comment.confirmedPhone = true order by comment.createdOn desc';
-         $commentQuery = $this->entityManager->createQuery($dql);
-         $commentQuery->setMaxResults(3);
-         return $commentQuery->getResult();
-     }
-     public function getTopCityList() {
-         return $this->entityManager->getRepository(City::class)->findBy(['parent' => null], ['ID' => 'ASC']);
-     }
-     public function getCityList() {
-         return $this->entityManager->getRepository(City::class)->getCitiesSorted();
-     }
-     public function getCategoriesList($domainObjectID, $cityID = City::DEFAULT_CITY_ID) {
-         return $this->entityManager->getRepository(Category::class)->getCategoryTree($domainObjectID, 0, $cityID);
-     }
-     public function getTopLevelCategories() {
-         $categoryRepository = $this->entityManager->getRepository(Category::class);
-         return $categoryRepository->getTopLevelOfferCategories($this->request->getSession()->get(City::CITY_ID_SESSION_KEY, City::DEFAULT_CITY_ID));
-     }
-     public function getURL($action, $entityID, $withDomain = false) {
-         $url = "";
-         $seoRepository = $this->entityManager->getRepository(Seo::class);
-         $seo = $seoRepository->getByEntity($action, $entityID);
-         if ($seo) {
-             $url = $seo->getMainAlias();
-             if ($withDomain) {
-                 $url = 'https://' . $seo->getDomain() . '.slivki.by' . $url;
-             }
-         }
-         return $url;
-     }
-     public function getCategoryURL(Category $category) {
-         return $this->entityManager->getRepository(Seo::class)->getCategoryURL($category);
-     }
-     public function getImageURL($media = null, $width, $height) {
-         $imageUrl = ImageService::FALLBACK_IMAGE;
-         if (!$media) {
-             return $imageUrl;
-         }
-         try {
-             $imageUrl = $this->imageService->getImageURLCached($media, $width, $height);
-         } catch (Exception $exception) {
-             $logger = Logger::instance('TwigExtension');
-             $logger->info('Media ID = ' . $media->getID() . ', file = ' . $media->getPath() . $media->getName() . ' not found in getImageURL!');
-         }
-         return $imageUrl;
-     }
-     public function getProfileImageURL($media, $width, $height) {
-         if (!$media) {
-             return ImageService::DEFAULT_AVATAR;
-         }
-         return $this->imageService->getImageURL($media, $width, $height);
-     }
-     public function getMetaInfo() {
-         $metaInfo = $this->request->attributes->get(SiteController::PARAMETER_META_INFO);
-         if ($metaInfo) {
-             $metaInfo = array(
-                 "title" => $metaInfo->getTitle(),
-                 "metaTitle" => $metaInfo->getMetaTitle(),
-                 "metaDescription" => $metaInfo->getMetaDescription(),
-                 "metaKeywords" => $metaInfo->getMetaKeywords()
-             );
-         } else {
-             $metaInfo = array(
-                 "title" => '',
-                 "metaTitle" => "Скидки в Минске! Акции и распродажи на Slivki.by!",
-                 "metaDescription" => "Грандиозные скидки и акции в Минске: рестораны, салоны красоты, клубы, спорт, досуг... Лучшие цены в популярных заведениях и магазинах Минска на Slivki.by!",
-                 "metaKeywords" => "скидки, распродажи, рекламные акции, Минск, кредит, дисконтная карта, карточка, новогодние скидки, Сезонные Распродажи и скидки, праздничная распродажа, распродажа одежды, приз, подарок, сюрприз, сувенир, РБ, Республика Беларусь, единая дисконтная система Беларуси, выгода, товары и услуги выгодно, экономия, промо, Акция, магазин, успеть купить, Модная одежда, фирмы, компании, рестораны, Минск, сезон потребитель дешево качественно быстро удобно продавец Новый товар"
-             );
-         }
-         return $metaInfo;
-     }
-     public function getSidebar(Environment $environment, $categoryID = null): string
-     {
-         if (!$this->serverFeatureStateChecker->isServerFeatureEnabled(SwitcherFeatures::SALES())) {
-             return $environment->render('Slivki/uz/sidebar.html.twig');
-         }
-         $sidebarCached = $this->sidebarCacheService->getSidebarCached();
-         if (null === $sidebarCached) {
-             return '';
-         }
-         return $sidebarCached->getFirstPage();
-     }
-     public function getBannerCodeFromFile($banner) {
-         $filePath = realpath($this->kernel->getProjectDir() . '/public') . $banner->getCodeFilePath();
-         $fileContent = @file_get_contents($filePath);
-         return $fileContent;
-     }
-     /**
-      * @return \Slivki\Entity\SiteSettings
-      */
-     public function getSiteSettings() {
-         $softCache = new SoftCache("");
-         $cacheKey = SiteSettingsRepository::CACHE_NAME;
-         $settingsCached = $softCache->get($cacheKey);
-         if ($settingsCached) {
-             return $settingsCached;
-         }
-         $settingsCached = $this->entityManager->getRepository(SiteSettings::class)->findAll();
-         $settingsCached = $settingsCached[0];
-         $softCache->set($cacheKey, $settingsCached, 60 * 60);
-         return $settingsCached;
-     }
-     public function staticCall($function, $arguments = []) {
-         return call_user_func($function, $arguments);
-     }
-     public function getStatVisitCount($entityID, $entityType, $dateFrom, $dateTo) {
-         $entityManager = $this->entityManager;
-         switch ($entityType) {
-             case Visit::TYPE_MALL_ALL_PAGES:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_MALL_MAIN_PAGE.",".Visit::TYPE_MALL_DETAILS.",".Visit::TYPE_MALL_BRAND.")";
-                 break;
-             case Visit::TYPE_SLIVKI_TV_ALL:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SLIVKI_TV_GUIDES.")";
-                 break;
-             case Visit::TYPE_FLIER_ALL:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_FLIER_DETAILS.")";
-                 break;
-             case Visit::TYPE_OFFERS_ALL:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER.")";
-                 break;
-             case Visit::TYPE_OFFER_CATEGORIES_ALL:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER_CATEGORY.")";
-                 break;
-             case Visit::TYPE_SALE_ALL:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SALE.")";
-                 break;
-             case Visit::TYPE_SALE_CATEGORIES_ALL: {
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SALE_CATEGORY.")";
-                 break;
-             }
-             case Visit::TYPE_OFFER_BY_CATEGORY:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER.") and entity_id in (select entity_id from category2entity where category_id = ".$entityID.")";
-                 break;
-             case Visit::TYPE_OFFER_BY_CATEGORY_REF:
-                 $sql = "select sum(visit_count_ref) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_OFFER.") and entity_id in (select entity_id from category2entity where category_id = ".$entityID.")";
-                 break;
-             case Visit::TYPE_FLIER_CATEGORIES_ALL: {
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_FLIER_CATEGORY.")";
-                 break;
-             }
-             case Visit::TYPE_SLIVKI_TV_CATEGORIES_ALL: {
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_type_id in (".Visit::TYPE_SLIVKI_TV_CATEGORIES_ALL.")";
-                 break;
-             }
-             default:
-                 $sql = "select sum(visit_count) from stat_visit_count_aggregated where visit_date >= '$dateFrom' and visit_date <= '$dateTo' and entity_id = $entityID and entity_type_id = $entityType";
-                 break;
-         }
-         $count = $entityManager->getConnection()->executeQuery($sql)->fetchColumn();
-         return $count ? $count : 0;
-     }
-     public function getVisitCount($id, $type, $increment = true) {
-         return $this->entityManager->getRepository(Visit::class)->getVisitCount($id, $type, $increment);
-     }
-     public function getOfferVisitCount($offer, $today = false) {
-         if ($today) {
-             return $this->entityManager->getRepository(Offer::class)->getVisitCount($offer, true);
-         }
-         return $this->entityManager->getRepository(Visit::class)->getVisitCount($offer->getID(), Visit::TYPE_OFFER, 30);
-     }
-     public function getOfferConversion($offerID) {
-         $entityManager = $this->entityManager;
-         $visitRepository = $entityManager->getRepository(Visit::class);
-         $purchaseCountRepository = $entityManager->getRepository(PurchaseCount::class);
-         $visitCount = $visitRepository->getVisitCount($offerID, Visit::TYPE_OFFER, 30);
-         $purchaseCount = $purchaseCountRepository->findOneBy(['entityID' => $offerID]);
-         if (!$visitCount || !$purchaseCount || !$purchaseCount->getPurchaseCountLastMonthWithCorrection()) {
-             return 0;
-         }
-         return ceil(100 * ($purchaseCount->getPurchaseCountLastMonthWithCorrection() / $visitCount));
-     }
-     public function getSaleVisitCount($saleID, $daysCount = 30, $reload = false) { //TODO: Use one function for all types
-         return $this->entityManager->getRepository(Visit::class)->getVisitCount($saleID, Category::SALE_CATEGORY_ID, $daysCount, $reload);
-     }
-     public function getVideoGuideVisitCount($saleID) {
-         return $this->entityManager->getRepository(VisitCounter::class)->getVisitCount($saleID, VisitCounter::TYPE_SALE, false);
-     }
-     public function getOfferMonthlyPurchaseCount(int $offerId): int
-     {
-         return $this->purchaseCountDao->getLastMonthWithCorrectionByOfferId($offerId);
-     }
-     public function getBankCurrencyList() {
-         return $this->entityManager->getRepository(BankCurrency::class)->findBy([], ['ID' => 'ASC']);
-     }
-     public function getCategoryBreadcrumbs(Category $category) {
-         return $this->entityManager->getRepository(Category::class)->getCategoryBreadcrumbs($category);
-     }
-     public function getCommentEntityByType($entityID, $typeID) {
-         return $this->entityManager->getRepository(Comment::class)->getCommentEntity($entityID, $typeID);
-     }
-     public function getCommentsCountByUserID($userID, $entityID, $typeID) {
-         return $this->entityManager->getRepository(Comment::class)->getCommentsCountByUserID($userID, $entityID, $typeID);
-     }
-     public function getMainMenu(Environment $twig, $showStatistics, $oldTemplate = true) { //TODO: Pass all data to view directly
-         $mobileDevice = $this->isMobileDevice();
-         $cityID = $this->request->getSession()->get(City::CITY_ID_SESSION_KEY, City::DEFAULT_CITY_ID);
-         $type = null;
-         if ($showStatistics) {
-             $type = TextCacheService::MAIN_MENU_STATISTICS_TYPE;
-         } else  {
-             $type = $mobileDevice ? TextCacheService::MAIN_MENU_MOBILE_TYPE : TextCacheService::MAIN_MENU_TYPE;
-         }
-         if ($mobileDevice && $oldTemplate) {
-             $type = TextCacheService::MAIN_MENU_OLD_MOBILE_TYPE;
-         }
-         $textCacheService = $this->textCacheService;
-         $mainMenu = $textCacheService->getText($cityID, $type, true);
-         if ($mainMenu) {
-             if (!$mobileDevice) {
-                 $mainMenuBanner = '';
-                 $mainMenuBanners = $this->bannerService->getMainMenuBannerCached();
-                 if ($mainMenuBanners) {
-                     $mainMenuBannersCount = count($mainMenuBanners);
-                     $currentMainMenuBannerIndex = $this->request->cookies->get('mainMenuBanner', -1);
-                     if ($currentMainMenuBannerIndex == $mainMenuBannersCount - 1) {
-                         $currentMainMenuBannerIndex = 0;
-                     } else {
-                         $currentMainMenuBannerIndex++;
-                     }
-                     if (isset($mainMenuBanners[$currentMainMenuBannerIndex])) {
-                         $mainMenuBanner = $mainMenuBanners[$currentMainMenuBannerIndex];
-                     }
-                 }
-                 $mainMenu[3] = str_replace('||mainMenuBannerPlaceholder||', $mainMenuBanner, $mainMenu[3]);
-             }
-             return $mainMenu[3];
-         }
-         return '';
-     }
-     public function getCommentsMenuItems() {
-         return $this->entityManager->getRepository(Comment::class)->getTopMenu();
-     }
-     public function getActiveSubCategories($categoryID) {
-         $city = $this->getCurrentCity();
-         return $this->entityManager->getRepository(Category::class)->getActiveCategories(
-             $categoryID, [Category::DEFAULT_CATEGORY_TYPE, Category::SERVICE_CATEGORY_TYPE], Category::OFFER_CATEGORY_ID, $city->getID());
-     }
-     public function getTestMenuItem($itemID)
-     {
-         $keySuffix = self::isMobileDevice() ? 'Mobile' : '';
-         switch ($itemID) {
-             case 0:
-                 if (!self::$photoGuideMenuItem) {
-                     $url = $this->getURL(SeoRepository::RESOURCE_URL_SALE_CATEGORY, Category::PHOTOGUIDE_SALE_CATEGORY_ID);
-                     self::$photoGuideMenuItem = ['name' => 'Фотогиды', 'url' => $url];
-                 }
-                 return self::$photoGuideMenuItem;
-             case 1:
-                 return ['name' => 'Новости скидок', 'url' => '/skidki-i-rasprodazhi'];
-             case 2:
-                 return ['name' => 'e-Товары', 'abKey' => 'e-tovary' . $keySuffix];
-         }
-         return null;
-     }
-     public function getActiveSalesCount() {
-         return $this->entityManager->getRepository(Sale::class)->getActiveSalesCountCached();
-     }
-     public function getActiveOffersCount($cityID = City::DEFAULT_CITY_ID) {
-         return $this->entityManager->getRepository(Offer::class)->getActiveOffersCountCached($cityID);
-     }
-     public function getPartnerLogoURL($partnerID) {
-         if ($this->partnerLogoURL) {
-             //return $this->partnerLogoURL;
-         }
-         $media = $this->entityManager->getRepository(Media::class)->getMedia($partnerID, MediaType::TYPE_PARTNER_LOGO_ID);
-         if ($media) {
-             $this->partnerLogoURL = $this->imageService->getImageURLCached($media[0], 86, 0);
-         } else {
-             $this->partnerLogoURL = ImageService::FALLBACK_IMAGE;;
-         }
-         return $this->partnerLogoURL;
-     }
-     /**
-      * Detect & return the ending for the plural word
-      *
-      * @param  integer $endings  nouns or endings words for (1, 4, 5)
-      * @param  array   $number   number rows to ending determine
-      *
-      * @return string
-      *
-      * @example:
-      * {{ ['Остался %d час', 'Осталось %d часа', 'Осталось %d часов']|plural(11) }}
-      * {{ count }} стат{{ ['ья','ьи','ей']|plural(count)
-      */
-     function pluralFilter($endings, $number) {
-         return CommonUtil::plural($endings, $number);
-     }
-     function pregReplaceFilter($str, $pattern, $replacement) {
-         return preg_replace($pattern, $replacement, $str);
-     }
-     public function localizeDateFilter(DateTimeInterface $dateTime, $format, $locale = 'ru_Ru'): string
-     {
-         return (new IntlDateFormatter(
-             $locale,
-             IntlDateFormatter::NONE,
-             IntlDateFormatter::NONE,
-             date_default_timezone_get(),
-             IntlDateFormatter::GREGORIAN,
-             $format
-         ))->format($dateTime);
-     }
-     public function localizeDateTimestampFilter(string $timestamp, string $format, string $locale = 'ru_Ru'): string
-     {
-         return (new \IntlDateFormatter(
-             $locale,
-             \IntlDateFormatter::NONE,
-             \IntlDateFormatter::NONE,
-             date_default_timezone_get(),
-             \IntlDateFormatter::GREGORIAN,
-             $format
-         ))->format((new \DateTimeImmutable())->setTimestamp($timestamp));
-     }
-     function phoneFilter($number) {
-         if ($number != (int)$number || strlen((string)$number) != 12) {
-             return $number;
-         }
-         return substr($number,5,3) . ' ' .  substr($number,8,2) . ' '
-             . substr($number,10,2);
-     }
-     function jsonDecodeFilter($json) {
-         return json_decode($json);
-     }
-     /**
-      * @param $var
-      * @param $instance
-      * @return bool
-      */
-     public function isInstanceof($var, $instance) {
-         return  $var instanceof $instance;
-     }
-     public function isObject($var) {
-         return is_object($var);
-     }
-     public function getName() {
-         return "slivki_extension";
-     }
-     public function getSaleShortDescription(Sale $sale) {
-         $saleDescriptions = $sale->getDescriptions();
-         if (!$saleDescriptions || $saleDescriptions->count() == 0) {
-             return '';
-         }
-         $description = $sale->getDescriptions()->first()->getDescription();
-         $crawler = new Crawler();
-         $crawler->addHtmlContent($description);
-         $pList = $crawler->filter('p');
-         $i = 0;
-         $shortDescription = '';
-         foreach ($pList as $domElement) {
-             $p = htmlentities($domElement->textContent, null, 'utf-8');
-             $p = trim(str_replace(" ", " ", $p));
-             $p = html_entity_decode($p);
-             if (strlen($p) > 0) {
-                 $i++;
-                 if($i == 2) {
-                     $shortDescription = $p;
-                     break;
-                 }
-             }
-         }
-         $shortDescription = strip_tags($shortDescription);
-         return $shortDescription;
-     }
-     public function getSupplierOfferPhotoBlockByOfferID(Environment $twig, $offerID) {
-         $perPage = 20;
-         $mediaList = $this->cacheService->getMediaList($offerID,OfferSupplierPhotoMedia::TYPE, 0, 0, $perPage);
-         if (empty($mediaList)) {
-             return '';
-         }
-         $data = [
-             'offerID' => $offerID,
-             'supplierOfferPhotoList' => $mediaList
-         ];
-         $data['supplierOfferPhotoList'] = array_slice($data['supplierOfferPhotoList'], 0, 20);
-         return $twig->render('Slivki/comments/offer_supplier_photo_block.html.twig', $data);
-     }
-     public function getUserCommentsMediaBlockByEntityID(Environment $twig, $entityID, $entityType) {
-         $data['commentAndMediaList'] = [];
-         switch ($entityType) {
-             case 'category':
-                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaListByCategoryID($entityID);
-                 break;
-             case 'offer':
-                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaListByOfferID($entityID);
-                 break;
-             case 'all':
-                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaList();
-                 break;
-         }
-         $data['entityID'] = $entityID;
-         $data['entityType'] = $entityType;
-         if(empty($data['commentAndMediaList'])) {
-             return '';
-         }
-         $html = $twig->render('Slivki/comments/media_block.html.twig', $data);
-         return $html;
-     }
-     public function getEntityRatingWithCount($entityType, $entityID, $dateFrom = false, $dateTo = false) {
-         return $this->entityManager->getRepository(Comment::class)->getEntityRatingWithCount($entityType, $entityID, $dateFrom, $dateTo);
-     }
-     public function getCompaniesRatingBlock(Environment $twig, $categoryID, $isMobile = false) {
-         $type = $isMobile ? TextCacheService::COMPANIES_RATING_MOBILE_TYPE : TextCacheService::COMPANIES_RATING_TYPE;
-         $html = $this->textCacheService->getText($categoryID, $type);
-         if (!$html || $html == '') { //TODO: remove
-             $softCache = new SoftCache(OfferRepository::CACHE_NAME);
-             $mobileCacheName = $isMobile ? 'mobile-' : '';
-             $html = $softCache->get('company-rating-data-' . '-' . $mobileCacheName . $categoryID);
-         }
-         return $html ? $html : '';
-     }
-     public function getMailingCampaignEntityPositionByEntityID($mailingCampaignID, $entityID, $entityType) {
-         $mailingCampaign = $this->entityManager->getRepository(MailingCampaign::class)->find($mailingCampaignID);
-         return $mailingCampaign->getEntityPositionByEntityID($entityID, $entityType);
-     }
-     public function getActiveCityList() {
-         return $this->entityManager->getRepository(City::class)->getActiveCitiesCached();
-     }
-     public function getActiveSortedCityList() {
-         return $this->entityManager->getRepository(City::class)->getActiveSortedCitiesCached();
-     }
-     public function getCurrentCity() {
-         return $this->entityManager->getRepository(City::class)->findCached($this->request->getSession()->get(City::CITY_ID_SESSION_KEY, City::DEFAULT_CITY_ID));
-     }
-     public function setSeenMicrophoneTooltip(User $user) {
-         if (!$user->isSeenMicrophoneTooltip()) {
-             $user = $this->entityManager->merge($user);
-             $user->setSeenMicrophoneTooltip();
-             $this->entityManager->flush($user);
-         }
-     }
-     public function getFlierProductCategories(Environment $twig) {
-         $dql = "select category from Slivki:ProductCategory category where category.parents is empty order by category.name ASC";
-         $categories = $this->entityManager->createQuery($dql)->getResult();
-         return $twig->render('Slivki/admin/sales/products/category_list.html.twig', ['categories' => $categories]);
-     }
-     public function getFlierProductSubCategories(Environment $twig, $categoryID) {
-         $categories = $this->entityManager->getRepository(ProductCategory::class)->find($categoryID);
-         $subCategories = $categories->getSubCategories();
-         return  $twig->render('Slivki/admin/sales/products/sub_category_list.html.twig', ['categories' => $subCategories]);
-     }
-     public function getIPLocationData() {
-         $defaultLocation = [53.902250, 27.561889];
-         return $defaultLocation;
-         $data = $this->entityManager->getRepository(City::class)->getIPLocationData($this->request);
-         if (!$data) {
-             return $defaultLocation;
-         }
-         return [$data['latitude'], $data['longitude']];
-     }
-     public function isInDefaultCity() {
-         return City::DEFAULT_CITY_ID == $this->entityManager->getRepository(City::class)->getCityIDByGeoIP($this->request);
-     }
-     public function isTireDirector($userID) {
-         return $this->entityManager->getRepository(Director::class)->isTireDirector($userID);
-     }
-     public function getCurrentCityURL() {
-         $cityID = $this->request->getSession()->get(City::CITY_ID_SESSION_KEY, City::DEFAULT_CITY_ID);
-         if ($cityID == City::DEFAULT_CITY_ID) {
-             return '/';
-         }
-         return $this->entityManager->getRepository(Seo::class)->getCityURL($cityID);
-     }
-     public function showMyPromocodesMenuItem(User $user) {
-         $userRepository = $this->entityManager->getRepository(User::class);
-         $lastBuyDate = $userRepository->getLastBuyDate($user);
-         if (!$lastBuyDate) {
-             return false;
-         }
-         return time() - $lastBuyDate->format('U') < 30 * 24 * 3600;
-     }
-     public function getFooter(Environment $twig): string
-     {
-         $mobile = $this->isMobileDevice();
-         $footerVersion = rand(0, 1);
-         $cacheKey = 'footer-2-' . $this->getCurrentCity()->getID() . '-'  . ($mobile ? '-mobile' : '') . '-' . $footerVersion;
-         $softCache = new SoftCache('');
-         $footer = $softCache->getDataWithLock($cacheKey);
-         if (!$footer) {
-             $view = sprintf(
-                 'Slivki%s/footer%s.html.twig',
-                 $this->parameterBag->get('regional_template_path'),
-                 $mobile ? '_mobile' : '',
-             );
-             $footer = $twig->render($view, ['footerVersion' => $footerVersion]);
-             $data = ['data' => $footer, 'expDate' => time() + 60 * 60];
-             $softCache->set($cacheKey, $data, 0);
-         }
-         return $footer;
-     }
-     public function getSaleCategoriesSortedBySaleVisits() {
-         return $this->entityManager->getRepository(Category::class)->getSaleCategoriesSortedBySaleVisits();
-     }
-     public function addLazyAndLightboxImagesInDescription($description) {
-         if (trim($description) == '') {
-             return '';
-         }
-         $html = new Crawler();
-         $html->addHtmlContent($description);
-         $nodeList = $html->filter('img');
-         if (!empty($nodeList)) {
-             $nodeList->each(function (Crawler $node) {
-                 $nodeElem = $node->getNode(0);
-                 $source = $nodeElem->getAttribute('src');
-                 $dataOriginal = $nodeElem->getAttribute('data-original');
-                 if ($source and !$dataOriginal) {
-                     $nodeElem->setAttribute('src', '/common-img/d.gif');
-                     $nodeElem->setAttribute('data-original', $source);
-                     $nodeElem->setAttribute('class', 'sale-lazy-spin');
-                     $parentElem = $node->parents()->first()->getNode(0);
-                     $ratio = $nodeElem->getAttribute('data-ratio');
-                     if ($ratio != '') {
-                         $newParentNode = new \DOMElement('div');
-                         $parentElem->replaceChild($newParentNode, $nodeElem);
-                         $newParentNode->setAttribute('class', 'sale-lazy-wrap');
-                         $width = $nodeElem->getAttribute('width');
-                         $style = $nodeElem->getAttribute('style');
-                         $newParentNode->setAttribute('style', 'max-width:' . $width. 'px;' . $style);
-                         $nodeForPadding =  new \DOMElement('div');
-                         $newParentNode->appendChild($nodeForPadding);
-                         $nodeForPadding->setAttribute('style', 'padding-bottom:' . $ratio. '%');
-                         $newParentNode->appendChild($nodeElem);
-                     }
-                 }
-             });
-         }
-         if (self::isMobileDevice()) {
-             $nodeList = $html->filter('iframe');
-             if (!empty($nodeList)) {
-                 $nodeList->each(function (Crawler $node) {
-                     $nodeElem = $node->getNode(0);
-                     $source = $nodeElem->getAttribute('src');
-                     if (strpos($source, 'youtube') !== false) {
-                         $parentElem = $node->parents()->first()->getNode(0);
-                         $newParentNode = new \DOMElement('div');
-                         $parentElem->replaceChild($newParentNode, $nodeElem);
-                         $newParentNode->setAttribute('class', 'embed-responsive embed-responsive-16by9');
-                         $nodeElem->setAttribute('class', 'embed-responsive-item');
-                         $newParentNode->appendChild($nodeElem);
-                     }
-                 });
-             }
-         }
-         $result = str_replace('<body>', '', $html->html());
-         $result = str_replace('</body>', '', $result);
-         return $result;
-     }
-     public function getMedia($entityID, $type) {
-         $mediaList = $this->entityManager->getRepository(Media::class)->getMedia($entityID, $type);
-         return $mediaList ? $mediaList[0] : null;
-     }
-     public function logWrite($data) {
-         Logger::instance('TWIG LOG WRITER')->info(print_r($data, true));
-     }
-     public function getManagerPhoneNumber($offset = 0) {
-         switch ($this->getCurrentCity()->getID()) {
-             case 5:
-                 return '+375 29 380 03 33';
-             case 2:
-                 return '+375 29 678 53 32';
-             default:
-                 return '+375 29 508 44 44';
-         }
-     }
-     public function calcDeliveryPriceOffer(
-         $extension,
-         $pickupDeliveryType,
-         $regularPrice,
-         $priceOffer,
-         ?OfferExtensionVariant $extensionVariant
-     )
-     {
-         return PriceDeliveryType::calcDeliveryPickupPrice(
-             $extension,
-             $pickupDeliveryType,
-             $regularPrice,
-             $priceOffer,
-             $extensionVariant
-         );
-     }
-     public function getSocialProviderLoginUrl($socialNetwork, $goto) {
-         $className = 'Slivki\Util\OAuth2Client\Provider\\' . ucfirst($socialNetwork) . 'Client';
-         /** @var AbstractOAuth2Client $oAuthProvider */
-         $oAuthProvider = new $className();
-         return $oAuthProvider->getLoginUrl($goto);
-     }
-     public function isProductFastDelivery($director): bool
-     {
-         if (null === $director) {
-             return false;
-         }
-         $offers = $director->getOffers();
-         /** @var ProductFastDeliveryRepository $deliveryFastRepository */
-         $deliveryFastRepository = $this->entityManager->getRepository(ProductFastDelivery::class);
-         /** @var Offer $offerItem */
-         foreach ($offers as $offerItem) {
-             if ($offerItem->isActive()) {
-                 $times = $deliveryFastRepository->getFastDeliveryProductsByOffer($offerItem);
-                 if ($times) {
-                     return true;
-                 }
-             }
-         }
-         return false;
-     }
-     public function calcDishDiscount($regularPrice, $offerPrice) {
-         $offerPrice = (float)$offerPrice;
-         $regularPrice = (float)$regularPrice;
-         if ($regularPrice == 0) {
-             return 0;
-         }
-         return \round(100 - ($offerPrice / $regularPrice * 100));
-     }
-     public function getRTBHouseUID(User $user = null) {
-         return $this->RTBHouseService->getUID($user);
-     }
-     public function getVimeoEmbedPreview($videoId)
-     {
-         $config = $this->videoConfigService->config($videoId);
-         if (isset($config['video']['thumbs'])
-             && \is_array($config['video']['thumbs'])
-             && \count($config['video']['thumbs']) > 0
-         ) {
-             return \reset($config['video']['thumbs']);
-         }
-         return '';
-     }
-     public function getUserBalanceCodesCount(User $user, $cityID) {
-         return $this->entityManager->getRepository(User::class)->getUserBalanceCodesCount($user, $cityID);
-     }
-     public function showAppInviteModal(User $user = null) : bool {
-         if (!$user) {
-             return true;
-         }
-         $sql = 'select max(created_on) from offer_order'
-             .' where status > 0 and device_type = ' . SiteController::DEVICE_TYPE_MOBILE_APP
-             . ' and user_id = ' . $user->getID();
-         $userLastAppPurchaseDate = $this->entityManager->getConnection()->executeQuery($sql)->fetchColumn();
-         if (!$userLastAppPurchaseDate) {
-             return true;
-         }
-         return (new \DateTime($userLastAppPurchaseDate) < (new \DateTime())->modify('-1 month'));
-     }
- }
-