src/Twig/SlivkiTwigExtension.php line 743

Open in your IDE?
  1. <?php
  2. namespace Slivki\Twig;
  3. use DateTimeInterface;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use IntlDateFormatter;
  6. use Slivki\BusinessFeature\OnlineOrder\Delivery\Twig\YandexDeliveryTwigRuntime;
  7. use Slivki\Controller\SiteController;
  8. use Slivki\Dao\OfferCode\PurchaseCountDaoInterface;
  9. use Slivki\Entity\BankCurrency;
  10. use Slivki\Entity\BrandingBanner;
  11. use Slivki\Entity\Category;
  12. use Slivki\Entity\CategoryType;
  13. use Slivki\Entity\City;
  14. use Slivki\Entity\Comment;
  15. use Slivki\Entity\Director;
  16. use Slivki\Entity\InfoPage;
  17. use Slivki\Entity\MailingCampaign;
  18. use Slivki\Entity\Media;
  19. use Slivki\Entity\Media\OfferSupplierPhotoMedia;
  20. use Slivki\Entity\MediaType;
  21. use Slivki\Entity\NoticePopup;
  22. use Slivki\Entity\NoticePopupView;
  23. use Slivki\Entity\Offer;
  24. use Slivki\Entity\OfferExtensionVariant;
  25. use Slivki\Entity\PriceDeliveryType;
  26. use Slivki\Entity\ProductCategory;
  27. use Slivki\Entity\ProductFastDelivery;
  28. use Slivki\Entity\Sale;
  29. use Slivki\Entity\Seo;
  30. use Slivki\Entity\SiteSettings;
  31. use Slivki\Entity\UserGroup;
  32. use Slivki\Entity\Visit;
  33. use Slivki\Entity\VisitCounter;
  34. use Slivki\Enum\SwitcherFeatures;
  35. use Slivki\Repository\OfferRepository;
  36. use Slivki\Repository\ProductFastDeliveryRepository;
  37. use Slivki\Repository\SeoRepository;
  38. use Slivki\Services\BannerService;
  39. use Slivki\Services\CacheService;
  40. use Slivki\Services\ImageService;
  41. use Slivki\Services\RTBHouseService;
  42. use Slivki\Services\Sidebar\SidebarCacheService;
  43. use Slivki\Services\Switcher\ServerFeatureStateChecker;
  44. use Slivki\Services\TextCacheService;
  45. use Slivki\Twig\Filter\PhoneNumberFilterTwigRuntime;
  46. use Slivki\Twig\Filter\ShortPriceFilterTwigRuntime;
  47. use Slivki\Util\OAuth2Client\AbstractOAuth2Client;
  48. use Slivki\Util\SoftCache;
  49. use Slivki\Util\CommonUtil;
  50. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  51. use Symfony\Component\HttpFoundation\RequestStack;
  52. use Slivki\Entity\User;
  53. use Slivki\Util\Logger;
  54. use Symfony\Component\DomCrawler\Crawler;
  55. use Symfony\Component\HttpFoundation\Session\Session;
  56. use Slivki\Repository\SiteSettingsRepository;
  57. use Symfony\Component\HttpKernel\KernelInterface;
  58. use Symfony\Component\Security\Acl\Exception\Exception;
  59. use Twig\Environment;
  60. use Twig\Extension\AbstractExtension;
  61. use Twig\TwigFilter;
  62. use Twig\TwigFunction;
  63. use Twig\TwigTest;
  64. class SlivkiTwigExtension extends AbstractExtension {
  65.     private $partnerLogoURL null;
  66.     private $entityManager;
  67.     private $request;
  68.     private $imageService;
  69.     private $bannerService;
  70.     private $textCacheService;
  71.     private $kernel;
  72.     private $cacheService;
  73.     private $RTBHouseService;
  74.     private static $photoGuideMenuItem null;
  75.     private SidebarCacheService $sidebarCacheService;
  76.     private ServerFeatureStateChecker $serverFeatureStateChecker;
  77.     private ParameterBagInterface $parameterBag;
  78.     private PurchaseCountDaoInterface $purchaseCountDao;
  79.     public function __construct(
  80.         EntityManagerInterface $entityManager,
  81.         RequestStack $requestStack,
  82.         ImageService $imageService,
  83.         BannerService $bannerService,
  84.         TextCacheService $textCacheService,
  85.         KernelInterface $kernel,
  86.         CacheService $cacheService,
  87.         RTBHouseService $RTBHouseService,
  88.         SidebarCacheService $sidebarCacheService,
  89.         ServerFeatureStateChecker $serverFeatureStateChecker,
  90.         ParameterBagInterface $parameterBag,
  91.         PurchaseCountDaoInterface $purchaseCountDao
  92.     ) {
  93.         $this->entityManager $entityManager;
  94.         $this->request $requestStack->getMainRequest();
  95.         $this->imageService $imageService;
  96.         $this->bannerService $bannerService;
  97.         $this->textCacheService $textCacheService;
  98.         $this->kernel $kernel;
  99.         $this->cacheService $cacheService;
  100.         $this->RTBHouseService $RTBHouseService;
  101.         $this->sidebarCacheService $sidebarCacheService;
  102.         $this->serverFeatureStateChecker $serverFeatureStateChecker;
  103.         $this->parameterBag $parameterBag;
  104.         $this->purchaseCountDao $purchaseCountDao;
  105.     }
  106.     public function getFilters(): array
  107.     {
  108.         return [
  109.             new TwigFilter('plural', [$this'pluralFilter']),
  110.             new TwigFilter('preg_replace', [$this'pregReplaceFilter']),
  111.             new TwigFilter('localizedate', [$this'localizeDateFilter']),
  112.             new TwigFilter('localize_timestamp_date', [$this'localizeDateTimestampFilter']),
  113.             new TwigFilter('phone', [$this'phoneFilter']),
  114.             new TwigFilter('json_decode', [$this'jsonDecodeFilter']),
  115.             new TwigFilter('short_price', [ShortPriceFilterTwigRuntime::class, 'shortPriceFormat']),
  116.             new TwigFilter('phone_number', [PhoneNumberFilterTwigRuntime::class, 'phoneNumberFormat']),
  117.         ];
  118.     }
  119.     public function getFunctions(): array
  120.     {
  121.         return [
  122.             new TwigFunction("getTopLevelCategories", array($this"getTopLevelCategories")),
  123.             new TwigFunction("getMetaInfo", array($this"getMetaInfo")),
  124.             new TwigFunction("getURL", array($this"getURL")),
  125.             new TwigFunction("getCategoryURL", array($this"getCategoryURL")),
  126.             new TwigFunction("getCategoriesList", array($this"getCategoriesList")),
  127.             new TwigFunction("getCityList", array($this"getCityList")),
  128.             new TwigFunction("getTopCityList", array($this"getTopCityList")),
  129.             new TwigFunction("getCategoryTypeList", array($this"getCategoryTypeList")),
  130.             new TwigFunction("getImageURL", array($this"getImageURL")),
  131.             new TwigFunction("getSidebar", [$this"getSidebar"], ['is_safe' => ['html'], 'needs_environment' => true]),
  132.             new TwigFunction("getProfileImageURL", [$this"getProfileImageURL"]),
  133.             new TwigFunction("getSiteSettings", [$this"getSiteSettings"]),
  134.             new TwigFunction("staticCall", [$this"staticCall"]),
  135.             new TwigFunction("getVisitCount",[$this"getVisitCount"]),
  136.             new TwigFunction("getOfferVisitCount",[$this"getOfferVisitCount"]),
  137.             new TwigFunction("getSaleVisitCount",[$this"getSaleVisitCount"]),
  138.             new TwigFunction("getVideoGuideVisitCount",[$this"getVideoGuideVisitCount"]),
  139.             new TwigFunction("getOfferMonthlyPurchaseCount",[$this"getOfferMonthlyPurchaseCount"]),
  140.             new TwigFunction("getTopSiteBanner",[$this"getTopSiteBanner"], ['is_safe' => ['html'], 'needs_environment' => false]),
  141.             new TwigFunction("getCategoryBanner",[$this"getCategoryBanner"]),
  142.             new TwigFunction('getCommentsBanners',[GetCommentsBanners::class, 'getCommentsBanners']),
  143.             new TwigFunction("getGoogleBanner",[$this"getGoogleBanner"], ['is_safe' => ['html'], 'needs_environment' => true]),
  144.             new TwigFunction("getBankCurrencyList", array($this"getBankCurrencyList")),
  145.             new TwigFunction("getCategoryBreadcrumbs", array($this"getCategoryBreadcrumbs")),
  146.             new TwigFunction("getLastComments", [$this"getLastComments"]),
  147.             new TwigFunction("getCommentEntityByType", [$this"getCommentEntityByType"]),
  148.             new TwigFunction("getCommentsMenuItems", [$this"getCommentsMenuItems"]),
  149.             new TwigFunction("getMainMenu", [$this"getMainMenu"], ['is_safe' => ['html'], 'needs_environment' => true]),
  150.             new TwigFunction("getActiveSubCategories", [$this"getActiveSubCategories"]),
  151.             new TwigFunction("getActiveSalesCount", [$this"getActiveSalesCount"]),
  152.             new TwigFunction("getActiveOffersCount", [$this"getActiveOffersCount"]),
  153.             new TwigFunction("getPartnerLogoURL", [$this"getPartnerLogoURL"]),
  154.             new TwigFunction("getCommentsCountByUserID", [$this"getCommentsCountByUserID"]),
  155.             new TwigFunction("getInfoPages", [$this"getInfoPages"]),
  156.             new TwigFunction("getSaleShortDescription", [$this"getSaleShortDescription"]),
  157.             new TwigFunction("isMobileDevice", [$this"isMobileDevice"]),
  158.             new TwigFunction("getNoticePopup", [$this"getNoticePopup"], ['is_safe' => ['html'], 'needs_environment' => true]),
  159.             new TwigFunction("getBrandingBanner", [$this"getBrandingBanner"], ['is_safe' => ['html'], 'needs_environment' => true]),
  160.             new TwigFunction("addSchemeAndHttpHostToImageSrc", [$this"addSchemeAndHttpHostToImageSrc"]),
  161.             new TwigFunction("getSupplierOfferPhotoBlockByOfferID", [$this"getSupplierOfferPhotoBlockByOfferID"], ['is_safe' => ['html'], 'needs_environment' => true]),
  162.             new TwigFunction("getUserCommentsMediaBlockByEntityID", [$this"getUserCommentsMediaBlockByEntityID"], ['is_safe' => ['html'], 'needs_environment' => true]),
  163.             new TwigFunction("getEntityRatingWithCount", [$this"getEntityRatingWithCount"]),
  164.             new TwigFunction("getInfoLine", [$this"getInfoLine"], ['is_safe' => ['html'], 'needs_environment' => true]),
  165.             new TwigFunction("getTeaserWatermark", [$this"getTeaserWatermark"]),
  166.             new TwigFunction("getCompaniesRatingBlock", [$this"getCompaniesRatingBlock"], ['is_safe' => ['html'], 'needs_environment' => true]),
  167.             new TwigFunction("getTestMenuItem", [$this"getTestMenuItem"]),
  168.             new TwigFunction("getMailingCampaignEntityPositionByEntityID", [$this"getMailingCampaignEntityPositionByEntityID"]),
  169.             new TwigFunction("getUsersOnlineCount", [$this"getUsersOnlineCount"]),
  170.             new TwigFunction("getActiveCityList", [$this"getActiveCityList"]),
  171.             new TwigFunction("getActiveSortedCityList", [$this"getActiveSortedCityList"]),
  172.             new TwigFunction("getCurrentCity", [$this"getCurrentCity"]),
  173.             new TwigFunction("setSeenMicrophoneTooltip", [$this"setSeenMicrophoneTooltip"]),
  174.             new TwigFunction("getFlierProductCategories", [$this"getFlierProductCategories"],  ['is_safe' => ['html'], 'needs_environment' => true]),
  175.             new TwigFunction("getFlierProductSubCategories", [$this"getFlierProductSubCategories"],  ['is_safe' => ['html'], 'needs_environment' => true]),
  176.             new TwigFunction("getIPLocationData", [$this"getIPLocationData"]),
  177.             new TwigFunction("isInDefaultCity", [$this"isInDefaultCity"]),
  178.             new TwigFunction("showMyPromocodesMenuItem", [$this"showMyPromocodesMenuItem"]),
  179.             new TwigFunction("getFooter", [$this"getFooter"],  ['is_safe' => ['html'], 'needs_environment' => true]),
  180.             new TwigFunction("addLazyAndLightboxImagesInDescription", [$this"addLazyAndLightboxImagesInDescription"]),
  181.             new TwigFunction("getStatVisitCount", [$this"getStatVisitCount"]),
  182.             new TwigFunction("getSaleCategoriesSortedBySaleVisits", [$this"getSaleCategoriesSortedBySaleVisits"]),
  183.             new TwigFunction("getMedia", [$this"getMedia"]),
  184.             new TwigFunction("logWrite", [$this"logWrite"]),
  185.             new TwigFunction('getLastVisitedOffersByUserId', [GetLastVisitedOffersTwigRuntime::class, 'getLastVisitedOffersByUserId']),
  186.             new TwigFunction("getManagerPhoneNumber", [$this"getManagerPhoneNumber"]),
  187.             new TwigFunction("getSocialProviderLoginUrl", [$this"getSocialProviderLoginUrl"]),
  188.             new TwigFunction("getBannerCodeFromFile", [$this"getBannerCodeFromFile"]),
  189.             new TwigFunction("getCurrentCityURL", [$this"getCurrentCityURL"]),
  190.             new TwigFunction("getMobileFloatingBanner", [MobileFloatingBannerRuntime::class, "getMobileFloatingBanner"]),
  191.             new TwigFunction("isTireDirector", [$this"isTireDirector"]),
  192.             new TwigFunction('isProductFastDelivery', [$this'isProductFastDelivery']),
  193.             new TwigFunction('calcDeliveryPriceOffer', [$this'calcDeliveryPriceOffer']),
  194.             new TwigFunction('calcDishDiscount', [$this'calcDishDiscount']),
  195.             new TwigFunction('getRTBHouseUID', [$this'getRTBHouseUID']),
  196.             new TwigFunction('getOfferConversion', [GetOfferConversionTwigRuntime::class, 'getOfferConversion']),
  197.             new TwigFunction('getVimeoEmbedPreview', [$this'getVimeoEmbedPreview']),
  198.             new TwigFunction('qrGeneratorMessage', [QRMessageGeneratorRuntime::class, 'qrGeneratorMessage']),
  199.             new TwigFunction('getFilterOrdersCount', [OnlineOrderHistoryTwigRuntime::class, 'getFilterOrdersCount']),
  200.             new TwigFunction('getUserBalanceCodesCount', [$this'getUserBalanceCodesCount']),
  201.             new TwigFunction('showAppInviteModal', [$this'showAppInviteModal']),
  202.             new TwigFunction('getOfferManagers', [UserGroupTwigRuntime::class, 'getOfferManagers']),
  203.             new TwigFunction('getLinkOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkOnlineOrder']),
  204.             new TwigFunction('getLinkFoodOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkFoodOnlineOrder']),
  205.             new TwigFunction('getLinkGiftCertificateOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkGiftCertificateOnlineOrder']),
  206.             new TwigFunction('getLinkGiftCertificateOnlineOrderByOnlyCode', [GetLinkOnlineOrderRuntime::class, 'getLinkGiftCertificateOnlineOrderByOnlyCode']),
  207.             new TwigFunction('getLinkTireOnlineOrder', [GetLinkOnlineOrderRuntime::class, 'getLinkTireOnlineOrder']),
  208.             new TwigFunction('isSubscriber', [SubscriptionTwigRuntime::class, 'isSubscriber']),
  209.             new TwigFunction('getSubscription', [SubscriptionTwigRuntime::class, 'getSubscription']),
  210.             new TwigFunction('getOfferCommentsCount', [GetCommentsCountTwigRuntime::class, 'getOfferCommentsCount']),
  211.             new TwigFunction('getDeliveryTimeText', [DeliveryTimeTextTwigRuntime::class, 'getDeliveryTimeText']),
  212.             new TwigFunction('getYandexDeliveryInfo', [YandexDeliveryTwigRuntime::class, 'getYandexDeliveryInfo']),
  213.             new TwigFunction('getCertificateAddresses', [GiftCertificateTwigRuntime::class, 'getCertificateAddresses']),
  214.             new TwigFunction('isServerFeatureEnabled', [ServerFeatureStateTwigRuntime::class, 'isServerFeatureEnabled']),
  215.             new TwigFunction('getDishNutrients', [GetDishNutrientsTwigRuntime::class, 'getDishNutrients']),
  216.             new TwigFunction('getUserAverageCommentRating', [GetUserAverageCommentRatingTwigRuntime::class, 'getUserAverageCommentRating']),
  217.             new TwigFunction('getGiftSubscription', [GiftSubscriptionRuntime::class, 'getSubscription']),
  218.             new TwigFunction('getVoiceMessage', [VoiceMessageTwigRuntime::class, 'getVoiceMessage']),
  219.             new TwigFunction('getPhoneOrEmailForActivity', [UserInfoForTransferActivityTwigRuntime::class, 'getPhoneOrEmailForActivity']),
  220.             new TwigFunction('isPartnerGiftOfferAvailable', [PartnerGiftOfferTwigRuntime::class, 'isPartnerGiftOfferAvailable']),
  221.         ];
  222.     }
  223.     public function getTests(): array
  224.     {
  225.         return [
  226.             new TwigTest('instanceof', [$this'isInstanceof']),
  227.             new TwigTest('object', [$this'isObject'])
  228.         ];
  229.     }
  230.     public function getTeaserWatermark($offerID) {
  231.         return $this->entityManager->getRepository(Offer::class)->getTeaserWatermark($offerID);
  232.     }
  233.     public function addSchemeAndHttpHostToImageSrc($text) {
  234.         $schemeAndHttpHost $this->request->getSchemeAndHttpHost();
  235.         return preg_replace('/(<img.*src=")(?!http)[\/]{0,1}([^"]*)/'"$1".$schemeAndHttpHost."/$2"$text);
  236.     }
  237.     public function getBrandingBanner(Environment $twig$user$categoryIDs = [], $offerID null) {
  238.         // TODO:: REFACTORING AND CACHING
  239.         $brandingBannerList = [];
  240.         if ($user && $user->getEmail() == 'kristina@slivki.by') {
  241.             $dql "select brandingBanner from Slivki:BrandingBanner brandingBanner where brandingBanner.test = :test order by brandingBanner.ID desc";
  242.             $brandingBannerList $this->entityManager->createQuery($dql)->setParameter('test'true)->getResult();
  243.         }
  244.         if (empty($brandingBannerList)) {
  245.             $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";
  246.             $brandingBannerList $this->entityManager->createQuery($dql)
  247.                 ->setParameter('timeFrom', new \DateTime())
  248.                 ->setParameter('timeTo', (new \DateTime())->modify('-1 day'))
  249.                 ->setParameter('test'false)->setParameter('active'true)
  250.                 ->getResult();
  251.             $bannersForCity = [];
  252.             $currentCityID = (int) $this->getCurrentCity()->getID();
  253.             foreach ($brandingBannerList as $key => $item) {
  254.                 if (in_array($currentCityID$item->getCityIds(), true)) {
  255.                     $bannersForCity[] = $item;
  256.                 } else {
  257.                     unset($brandingBannerList[$key]);
  258.                 }
  259.             }
  260.             if (!empty($bannersForCity)) {
  261.                 $brandingBannerList $bannersForCity;
  262.             }
  263.         }
  264.         $currentBrandingBanner = [];
  265.         $refreshCookie $this->request->cookies->get('refresh');
  266.         if (empty($categoryIDs) && strpos($this->request->headers->get('referer'), 'https://www.t.dev.slivki.by') === false && !$refreshCookie) {
  267.             foreach ($brandingBannerList as $branding) {
  268.                 if ($branding->getTitle() == 'yandex') {
  269.                     $currentBrandingBanner = [$branding];
  270.                 }
  271.             }
  272.         }
  273.         if (!$currentBrandingBanner) {
  274.             $breaker false;
  275.             $currentCategory null;
  276.             $categoryBrandingBannerList = [];
  277.             /** @var  BrandingBanner $item */
  278.             foreach ($categoryIDs as $categoryID) {
  279.                 $currentCategory $this->entityManager->getRepository(Category::class)->find($categoryID);
  280.                 if ($currentCategory) {
  281.                     /** @var BrandingBanner $brandingBanner */
  282.                     foreach ($brandingBannerList as $item) {
  283.                         if ($item->isPassThrough()) {
  284.                             $categoryBrandingBannerList[] = $item;
  285.                         } else if ($item->isForCategories()) {
  286.                             foreach ($item->getCategories() as $brandingBannerCategory) {
  287.                                 if ($brandingBannerCategory->getID() == $categoryID || $currentCategory->isChildOfRecursive($brandingBannerCategory->getID())) {
  288.                                     $categoryBrandingBannerList[] = $item;
  289.                                     break;
  290.                                 }
  291.                             }
  292.                         }
  293.                     }
  294.                 }
  295.             }
  296.             if (!empty($categoryBrandingBannerList)) {
  297.                 $brandingBannerList $categoryBrandingBannerList;
  298.             } else {
  299.                 foreach ($categoryIDs as $categoryID) {
  300.                     $currentCategory $this->entityManager->getRepository(Category::class)->find($categoryID);
  301.                     if ($currentCategory) {
  302.                         foreach ($brandingBannerList as $key=>$item) {
  303.                             $removeCategoryFlag true;
  304.                             if ($item->isForCategories() && !$item->isPassThrough()) {
  305.                                 foreach ($item->getCategories() as $brandingBannerCategory) {
  306.                                     if (in_array($brandingBannerCategory->getID(), $categoryIDs) || $currentCategory->isChildOfRecursive($brandingBannerCategory->getID())) {
  307.                                         $removeCategoryFlag false;
  308.                                         break;
  309.                                     }
  310.                                 }
  311.                                 if ($removeCategoryFlag) {
  312.                                     unset($brandingBannerList[$key]);
  313.                                 }
  314.                             }
  315.                         }
  316.                     }
  317.                 }
  318.                 if (empty($categoryIDs)) {
  319.                     foreach ($brandingBannerList as $key=>$item) {
  320.                         if ($item->isForCategories() && !$item->isPassThrough()) {
  321.                             unset($brandingBannerList[$key]);
  322.                         }
  323.                     }
  324.                 }
  325.             }
  326.             $brandingBannerList array_values(array_unique($brandingBannerListSORT_REGULAR));
  327.             if (!$this->isMobileDevice()) {
  328.                 foreach ($brandingBannerList as $brandingBanner) {
  329.                     if (empty($currentBrandingBanner) or $breaker == true) {
  330.                         $currentBrandingBanner $brandingBanner;
  331.                     }
  332.                     if ($breaker) {
  333.                         break;
  334.                     }
  335.                     if ($brandingBanner->getBannerID() == $this->request->cookies->get('fullSiteBanner1')) {
  336.                         $breaker true;
  337.                     }
  338.                 }
  339.             } else {
  340.                 foreach ($brandingBannerList as $brandingBanner) {
  341.                     if (($brandingBanner->getMobileImage() || $brandingBanner->getMobileDivider()) && (empty($currentBrandingBanner) || $breaker == true)) {
  342.                         $currentBrandingBanner $brandingBanner;
  343.                     }
  344.                     if ($breaker) {
  345.                         break;
  346.                     }
  347.                     if ($brandingBanner->getBannerID() == $this->request->cookies->get('fullSiteBanner1')) {
  348.                         $breaker true;
  349.                     }
  350.                 }
  351.             }
  352.         }
  353.         if (self::isMobileDevice()) {
  354.             return empty($currentBrandingBanner) ? null $currentBrandingBanner;
  355.         }
  356.         if (empty($currentBrandingBanner)) {
  357.             return '';
  358.         } else {
  359.             if (is_array($currentBrandingBanner)) {
  360.                 $currentBrandingBanner $currentBrandingBanner[0];
  361.             }
  362.             return $twig->render('Slivki/banners/branding_banner.html.twig', ['brandingBanner' => $currentBrandingBanner]);
  363.         }
  364.     }
  365.     public function getNoticePopup(Environment $twig$user) {
  366.         $noticePopup '';
  367.         $directorPopupID null;
  368.         try {
  369.             /** @var User $user */
  370.             if (($user && $user->hasRole(UserGroup::ROLE_SUPPLIER_ID))) {
  371.                 if (!$user->hasRole(UserGroup::ROLE_DIRECTOR_A) && !$user->hasRole(UserGroup::ROLE_DIRECTOR_B)) {
  372.                     $softCache = new SoftCache('director');
  373.                     $lastDirectorGroup $softCache->get('last_director_group'0);
  374.                     $lastDirectorGroup++;
  375.                     if ($lastDirectorGroup 1) {
  376.                         $lastDirectorGroup 0;
  377.                     }
  378.                     $softCache->set('last_director_group'$lastDirectorGroup0);
  379.                     if ($lastDirectorGroup == 0) {
  380.                         $role $this->entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_DIRECTOR_A);
  381.                         $user->addRole($role);
  382.                     } else {
  383.                         $role $this->entityManager->getRepository(UserGroup::class)->find(UserGroup::ROLE_DIRECTOR_B);
  384.                         $user->addRole($role);
  385.                     }
  386.                     $this->entityManager->flush();
  387.                 }
  388.                 if ($user->hasRole(UserGroup::ROLE_DIRECTOR_A)) {
  389.                     $directorPopupID NoticePopup::ID_DIRECTOR_A;
  390.                 } else {
  391.                     $directorPopupID NoticePopup::ID_DIRECTOR_B;
  392.                 }
  393.                 $noticePopup $this->getNoticePopupByID($twig$user$directorPopupID);
  394.             }
  395.             if ($noticePopup == '') {
  396.                 $noticePopup $this->getNoticePopupByID($twig$userNoticePopup::ID_USER);
  397.             }
  398.             if ($user && $user->getEmail() == 'volga@slivki.by') {
  399.                 $testPopups $this->entityManager->getRepository(NoticePopup::class)->findBy(['test' => true'type' => $directorPopupID]);
  400.                 if (isset($testPopups[0])) {
  401.                     $noticePopup $this->getNoticePopupByID($twig$user$testPopups[0]->getType());
  402.                 }
  403.             }
  404.         } catch (\Exception $e) {
  405.             Logger::instance('Notice popup error')->info($e->getMessage());
  406.             return '';
  407.         }
  408.         return $noticePopup;
  409.     }
  410.     private function getNoticePopupByID(Environment $twig$user$type) {
  411.         if ($this->isMobileDevice()) {
  412.             return '';
  413.         }
  414.         $dql 'select noticePopup from Slivki:NoticePopup noticePopup where noticePopup.active = true and noticePopup.type = :type and current_timestamp() between noticePopup.activeFrom and noticePopup.activeTill';
  415.         $noticePopupList $this->entityManager->createQuery($dql)->setParameter('type'$type)->getResult();
  416.         if (!$noticePopupList || count($noticePopupList) == 0) {
  417.             return '';
  418.         }
  419.         $noticePopup $noticePopupList[0];
  420.         if ($noticePopup->isTest() && $user && $user->getEmail() == 'volga@slivki.by') {
  421.             $noticePopupHtml $this->getNoticePopupHtmlView($twig$noticePopup);
  422.             return $noticePopupHtml == SoftCache::EMPTY_VALUE '' $noticePopupHtml;
  423.         }
  424.         if ($noticePopup) {
  425.             if ($this->isNoticePopupShown($noticePopup->getCookieName(), $user$noticePopup->getID())) {
  426.                 return '';
  427.             }
  428.         }
  429.         $noticePopupHtml $this->getNoticePopupHtmlView($twig$noticePopup);
  430.         return $noticePopupHtml == SoftCache::EMPTY_VALUE '' $noticePopupHtml;
  431.     }
  432.     private function getNoticePopupHtmlView(Environment $twig$noticePopup) {
  433.         $noticePopupID $noticePopup->getID();
  434.         $image $this->entityManager->getRepository(Media::class)
  435.             ->findOneBy(['entityID' => $noticePopupID'mediaType' => MediaType::TYPE_NOTICE_POPUP_IMAGE_ID], ['ID' => 'desc']);
  436.         $imageMobile $this->entityManager->getRepository(Media::class)
  437.             ->findOneBy(['entityID' => $noticePopupID'mediaType' => MediaType::TYPE_NOTICE_POPUP_IMAGE_ID_MOBILE], ['ID' => 'desc']);
  438.         return $twig->render('Slivki/popups/notice_popup.html.twig',
  439.             ['id'=> 'notice_popup''noticePopup' => $noticePopup'image' => $image'imageMobile' => $imageMobile]);
  440.     }
  441.     private function isNoticePopupShown($popupID$user$sessionKeySuffix) {
  442.         if (!$user) {
  443.             return false;
  444.         }
  445.         $session = new Session();
  446.         $sessionKey 'noticePopup' $sessionKeySuffix;
  447.         $noticePopupID $session->get($sessionKey);
  448.         if (!$noticePopupID) {
  449.             $popupView $this->entityManager->getRepository(NoticePopupView::class)->findBy(['popupID' => $popupID'userID' => $user->getID()]);
  450.             if (!$popupView) {
  451.                 $popupView = new NoticePopupView();
  452.                 $popupView->setCreatedOn(new \DateTime());
  453.                 $popupView->setPopupID($popupID);
  454.                 $popupView->setUserID($user->getID());
  455.                 $this->entityManager->persist($popupView);
  456.                 $this->entityManager->flush($popupView);
  457.                 return false;
  458.             }
  459.             $session->set($sessionKey$popupID);
  460.             return true;
  461.         }
  462.         if ($noticePopupID != $popupID) {
  463.             $session->set($sessionKey$popupID);
  464.             return false;
  465.         }
  466.         return true;
  467.     }
  468.     public function isMobileDevice() {
  469.         return CommonUtil::isMobileDevice($this->request);
  470.     }
  471.     public function getInfoPages($type) {
  472.         return $this->entityManager->getRepository(InfoPage::class)->getInfoPagesFromCache($type);
  473.     }
  474.     public function getTopSiteBanner($categoryIDs = [], $mobile$mobileCache false) {
  475.         return $this->bannerService->getHeadBannerCached($this->getCurrentCity()->getID(), $categoryIDs$mobile$mobileCache);
  476.     }
  477.     public function getCategoryBanner($categoryID) {
  478.         $categoryRepository $this->entityManager->getRepository(Category::class);
  479.         $category $categoryRepository->findCached($categoryID);
  480.         if (isset($category['category']) && $category['category'] instanceof Category) {
  481.             return $this->bannerService->getCategoryBannerCached($category['category'], self::isMobileDevice());
  482.         }
  483.         return '';
  484.     }
  485.     public function getGoogleBanner(Environment $twig) {
  486.         return $twig->render('Slivki/banners/head_banner_admixer.html.twig');
  487.     }
  488.     public function getCategoryTypeList() {
  489.         return $this->entityManager->getRepository(CategoryType::class)->findAll();
  490.     }
  491.     public function getLastComments() {
  492.         $dql 'select comment from Slivki:Comment comment where comment.hidden = false and comment.confirmedPhone = true order by comment.createdOn desc';
  493.         $commentQuery $this->entityManager->createQuery($dql);
  494.         $commentQuery->setMaxResults(3);
  495.         return $commentQuery->getResult();
  496.     }
  497.     public function getTopCityList() {
  498.         return $this->entityManager->getRepository(City::class)->findBy(['parent' => null], ['ID' => 'ASC']);
  499.     }
  500.     public function getCityList() {
  501.         return $this->entityManager->getRepository(City::class)->getCitiesSorted();
  502.     }
  503.     public function getCategoriesList($domainObjectID$cityID City::DEFAULT_CITY_ID) {
  504.         return $this->entityManager->getRepository(Category::class)->getCategoryTree($domainObjectID0$cityID);
  505.     }
  506.     public function getTopLevelCategories() {
  507.         $categoryRepository $this->entityManager->getRepository(Category::class);
  508.         return $categoryRepository->getTopLevelOfferCategories($this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID));
  509.     }
  510.     public function getURL($action$entityID$withDomain false) {
  511.         $url "";
  512.         $seoRepository $this->entityManager->getRepository(Seo::class);
  513.         $seo $seoRepository->getByEntity($action$entityID);
  514.         if ($seo) {
  515.             $url $seo->getMainAlias();
  516.             if ($withDomain) {
  517.                 $url 'https://' $seo->getDomain() . '.slivki.by' $url;
  518.             }
  519.         }
  520.         return $url;
  521.     }
  522.     public function getCategoryURL(Category $category) {
  523.         return $this->entityManager->getRepository(Seo::class)->getCategoryURL($category);
  524.     }
  525.     public function getImageURL($media null$width$height) {
  526.         $imageUrl ImageService::FALLBACK_IMAGE;
  527.         if (!$media) {
  528.             return $imageUrl;
  529.         }
  530.         try {
  531.             $imageUrl $this->imageService->getImageURLCached($media$width$height);
  532.         } catch (Exception $exception) {
  533.             $logger Logger::instance('TwigExtension');
  534.             $logger->info('Media ID = ' $media->getID() . ', file = ' $media->getPath() . $media->getName() . ' not found in getImageURL!');
  535.         }
  536.         return $imageUrl;
  537.     }
  538.     public function getProfileImageURL($media$width$height) {
  539.         if (!$media) {
  540.             return ImageService::DEFAULT_AVATAR;
  541.         }
  542.         return $this->imageService->getImageURL($media$width$height);
  543.     }
  544.     public function getMetaInfo() {
  545.         $metaInfo $this->request->attributes->get(SiteController::PARAMETER_META_INFO);
  546.         if ($metaInfo) {
  547.             $metaInfo = array(
  548.                 "title" => $metaInfo->getTitle(),
  549.                 "metaTitle" => $metaInfo->getMetaTitle(),
  550.                 "metaDescription" => $metaInfo->getMetaDescription(),
  551.                 "metaKeywords" => $metaInfo->getMetaKeywords()
  552.             );
  553.         } else {
  554.             $metaInfo = array(
  555.                 "title" => '',
  556.                 "metaTitle" => "Скидки в Минске! Акции и распродажи на Slivki.by!",
  557.                 "metaDescription" => "Грандиозные скидки и акции в Минске: рестораны, салоны красоты, клубы, спорт, досуг... Лучшие цены в популярных заведениях и магазинах Минска на Slivki.by!",
  558.                 "metaKeywords" => "скидки, распродажи, рекламные акции, Минск, кредит, дисконтная карта, карточка, новогодние скидки, Сезонные Распродажи и скидки, праздничная распродажа, распродажа одежды, приз, подарок, сюрприз, сувенир, РБ, Республика Беларусь, единая дисконтная система Беларуси, выгода, товары и услуги выгодно, экономия, промо, Акция, магазин, успеть купить, Модная одежда, фирмы, компании, рестораны, Минск, сезон потребитель дешево качественно быстро удобно продавец Новый товар"
  559.             );
  560.         }
  561.         return $metaInfo;
  562.     }
  563.     public function getSidebar(Environment $environment$categoryID null): string
  564.     {
  565.         if (!$this->serverFeatureStateChecker->isServerFeatureEnabled(SwitcherFeatures::SALES())) {
  566.             return $environment->render('Slivki/uz/sidebar.html.twig');
  567.         }
  568.         $sidebarCached $this->sidebarCacheService->getSidebarCached();
  569.         if (null === $sidebarCached) {
  570.             return '';
  571.         }
  572.         return $sidebarCached->getFirstPage();
  573.     }
  574.     public function getBannerCodeFromFile($banner) {
  575.         $filePath realpath($this->kernel->getProjectDir() . '/public') . $banner->getCodeFilePath();
  576.         $fileContent = @file_get_contents($filePath);
  577.         return $fileContent;
  578.     }
  579.     /**
  580.      * @return \Slivki\Entity\SiteSettings
  581.      */
  582.     public function getSiteSettings() {
  583.         $softCache = new SoftCache("");
  584.         $cacheKey SiteSettingsRepository::CACHE_NAME;
  585.         $settingsCached $softCache->get($cacheKey);
  586.         if ($settingsCached) {
  587.             return $settingsCached;
  588.         }
  589.         $settingsCached $this->entityManager->getRepository(SiteSettings::class)->findAll();
  590.         $settingsCached $settingsCached[0];
  591.         $softCache->set($cacheKey$settingsCached60 60);
  592.         return $settingsCached;
  593.     }
  594.     public function staticCall($function$arguments = []) {
  595.         return call_user_func($function$arguments);
  596.     }
  597.     public function getStatVisitCount($entityID$entityType$dateFrom$dateTo) {
  598.         $entityManager $this->entityManager;
  599.         switch ($entityType) {
  600.             case Visit::TYPE_SLIVKI_TV_ALL:
  601.                 $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.")";
  602.                 break;
  603.             case Visit::TYPE_FLIER_ALL:
  604.                 $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.")";
  605.                 break;
  606.             case Visit::TYPE_OFFERS_ALL:
  607.                 $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.")";
  608.                 break;
  609.             case Visit::TYPE_OFFER_CATEGORIES_ALL:
  610.                 $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.")";
  611.                 break;
  612.             case Visit::TYPE_SALE_ALL:
  613.                 $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.")";
  614.                 break;
  615.             case Visit::TYPE_SALE_CATEGORIES_ALL: {
  616.                 $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.")";
  617.                 break;
  618.             }
  619.             case Visit::TYPE_OFFER_BY_CATEGORY:
  620.                 $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.")";
  621.                 break;
  622.             case Visit::TYPE_OFFER_BY_CATEGORY_REF:
  623.                 $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.")";
  624.                 break;
  625.             case Visit::TYPE_FLIER_CATEGORIES_ALL: {
  626.                 $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.")";
  627.                 break;
  628.             }
  629.             case Visit::TYPE_SLIVKI_TV_CATEGORIES_ALL: {
  630.                 $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.")";
  631.                 break;
  632.             }
  633.             default:
  634.                 $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";
  635.                 break;
  636.         }
  637.         $count $entityManager->getConnection()->executeQuery($sql)->fetchColumn();
  638.         return $count $count 0;
  639.     }
  640.     public function getVisitCount($id$type$increment true) {
  641.         return $this->entityManager->getRepository(Visit::class)->getVisitCount($id$type$increment);
  642.     }
  643.     public function getOfferVisitCount($offer$today false) {
  644.         if ($today) {
  645.             return $this->entityManager->getRepository(Offer::class)->getVisitCount($offertrue);
  646.         }
  647.         return $this->entityManager->getRepository(Visit::class)->getVisitCount($offer->getID(), Visit::TYPE_OFFER30);
  648.     }
  649.     public function getSaleVisitCount($saleID$daysCount 30$reload false) { //TODO: Use one function for all types
  650.         return $this->entityManager->getRepository(Visit::class)->getVisitCount($saleIDCategory::SALE_CATEGORY_ID$daysCount$reload);
  651.     }
  652.     public function getVideoGuideVisitCount($saleID) {
  653.         return $this->entityManager->getRepository(VisitCounter::class)->getVisitCount($saleIDVisitCounter::TYPE_SALEfalse);
  654.     }
  655.     public function getOfferMonthlyPurchaseCount(int $offerId): int
  656.     {
  657.         return $this->purchaseCountDao->getLastMonthWithCorrectionByOfferId($offerId);
  658.     }
  659.     public function getBankCurrencyList() {
  660.         return $this->entityManager->getRepository(BankCurrency::class)->findBy([], ['ID' => 'ASC']);
  661.     }
  662.     public function getCategoryBreadcrumbs(Category $category) {
  663.         return $this->entityManager->getRepository(Category::class)->getCategoryBreadcrumbs($category);
  664.     }
  665.     public function getCommentEntityByType($entityID$typeID) {
  666.         return $this->entityManager->getRepository(Comment::class)->getCommentEntity($entityID$typeID);
  667.     }
  668.     public function getCommentsCountByUserID($userID$entityID$typeID) {
  669.         return $this->entityManager->getRepository(Comment::class)->getCommentsCountByUserID($userID$entityID$typeID);
  670.     }
  671.     public function getMainMenu(Environment $twig$showStatistics$oldTemplate true) { //TODO: Pass all data to view directly
  672.         $mobileDevice $this->isMobileDevice();
  673.         $cityID $this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID);
  674.         $type null;
  675.         if ($showStatistics) {
  676.             $type TextCacheService::MAIN_MENU_STATISTICS_TYPE;
  677.         } else  {
  678.             $type $mobileDevice TextCacheService::MAIN_MENU_MOBILE_TYPE TextCacheService::MAIN_MENU_TYPE;
  679.         }
  680.         if ($mobileDevice && $oldTemplate) {
  681.             $type TextCacheService::MAIN_MENU_OLD_MOBILE_TYPE;
  682.         }
  683.         $textCacheService $this->textCacheService;
  684.         $mainMenu $textCacheService->getText($cityID$typetrue);
  685.         if ($mainMenu) {
  686.             if (!$mobileDevice) {
  687.                 $mainMenuBanner '';
  688.                 $mainMenuBanners $this->bannerService->getMainMenuBannerCached();
  689.                 if ($mainMenuBanners) {
  690.                     $mainMenuBannersCount count($mainMenuBanners);
  691.                     $currentMainMenuBannerIndex $this->request->cookies->get('mainMenuBanner', -1);
  692.                     if ($currentMainMenuBannerIndex == $mainMenuBannersCount 1) {
  693.                         $currentMainMenuBannerIndex 0;
  694.                     } else {
  695.                         $currentMainMenuBannerIndex++;
  696.                     }
  697.                     if (isset($mainMenuBanners[$currentMainMenuBannerIndex])) {
  698.                         $mainMenuBanner $mainMenuBanners[$currentMainMenuBannerIndex];
  699.                     }
  700.                 }
  701.                 $mainMenu[3] = str_replace('||mainMenuBannerPlaceholder||'$mainMenuBanner$mainMenu[3]);
  702.             }
  703.             return $mainMenu[3];
  704.         }
  705.         return '';
  706.     }
  707.     public function getCommentsMenuItems() {
  708.         return $this->entityManager->getRepository(Comment::class)->getTopMenu();
  709.     }
  710.     public function getActiveSubCategories($categoryID) {
  711.         $city $this->getCurrentCity();
  712.         return $this->entityManager->getRepository(Category::class)->getActiveCategories(
  713.             $categoryID, [Category::DEFAULT_CATEGORY_TYPECategory::SERVICE_CATEGORY_TYPE], Category::OFFER_CATEGORY_ID$city->getID());
  714.     }
  715.     public function getTestMenuItem($itemID)
  716.     {
  717.         $keySuffix self::isMobileDevice() ? 'Mobile' '';
  718.         switch ($itemID) {
  719.             case 0:
  720.                 if (!self::$photoGuideMenuItem) {
  721.                     $url $this->getURL(SeoRepository::RESOURCE_URL_SALE_CATEGORYCategory::PHOTOGUIDE_SALE_CATEGORY_ID);
  722.                     self::$photoGuideMenuItem = ['name' => 'Фотогиды''url' => $url];
  723.                 }
  724.                 return self::$photoGuideMenuItem;
  725.             case 1:
  726.                 return ['name' => 'Новости скидок''url' => '/skidki-i-rasprodazhi'];
  727.             case 2:
  728.                 return ['name' => 'e-Товары''abKey' => 'e-tovary' $keySuffix];
  729.         }
  730.         return null;
  731.     }
  732.     public function getActiveSalesCount() {
  733.         return $this->entityManager->getRepository(Sale::class)->getActiveSalesCountCached();
  734.     }
  735.     public function getActiveOffersCount($cityID City::DEFAULT_CITY_ID) {
  736.         return $this->entityManager->getRepository(Offer::class)->getActiveOffersCountCached($cityID);
  737.     }
  738.     public function getPartnerLogoURL($partnerID) {
  739.         if ($this->partnerLogoURL) {
  740.             //return $this->partnerLogoURL;
  741.         }
  742.         $media $this->entityManager->getRepository(Media::class)->getMedia($partnerIDMediaType::TYPE_PARTNER_LOGO_ID);
  743.         if ($media) {
  744.             $this->partnerLogoURL $this->imageService->getImageURLCached($media[0], 860);
  745.         } else {
  746.             $this->partnerLogoURL ImageService::FALLBACK_IMAGE;;
  747.         }
  748.         return $this->partnerLogoURL;
  749.     }
  750.     /**
  751.      * Detect & return the ending for the plural word
  752.      *
  753.      * @param  integer $endings  nouns or endings words for (1, 4, 5)
  754.      * @param  array   $number   number rows to ending determine
  755.      *
  756.      * @return string
  757.      *
  758.      * @example:
  759.      * {{ ['Остался %d час', 'Осталось %d часа', 'Осталось %d часов']|plural(11) }}
  760.      * {{ count }} стат{{ ['ья','ьи','ей']|plural(count)
  761.      */
  762.     function pluralFilter($endings$number) {
  763.         return CommonUtil::plural($endings$number);
  764.     }
  765.     function pregReplaceFilter($str$pattern$replacement) {
  766.         return preg_replace($pattern$replacement$str);
  767.     }
  768.     public function localizeDateFilter(DateTimeInterface $dateTime$format$locale 'ru_Ru'): string
  769.     {
  770.         return (new IntlDateFormatter(
  771.             $locale,
  772.             IntlDateFormatter::NONE,
  773.             IntlDateFormatter::NONE,
  774.             date_default_timezone_get(),
  775.             IntlDateFormatter::GREGORIAN,
  776.             $format
  777.         ))->format($dateTime);
  778.     }
  779.     public function localizeDateTimestampFilter(string $timestampstring $formatstring $locale 'ru_Ru'): string
  780.     {
  781.         return (new \IntlDateFormatter(
  782.             $locale,
  783.             \IntlDateFormatter::NONE,
  784.             \IntlDateFormatter::NONE,
  785.             date_default_timezone_get(),
  786.             \IntlDateFormatter::GREGORIAN,
  787.             $format
  788.         ))->format((new \DateTimeImmutable())->setTimestamp($timestamp));
  789.     }
  790.     function phoneFilter($number) {
  791.         if ($number != (int)$number || strlen((string)$number) != 12) {
  792.             return $number;
  793.         }
  794.         return substr($number,5,3) . ' ' .  substr($number,8,2) . ' '
  795.             substr($number,10,2);
  796.     }
  797.     function jsonDecodeFilter($json) {
  798.         return json_decode($json);
  799.     }
  800.     /**
  801.      * @param $var
  802.      * @param $instance
  803.      * @return bool
  804.      */
  805.     public function isInstanceof($var$instance) {
  806.         return  $var instanceof $instance;
  807.     }
  808.     public function isObject($var) {
  809.         return is_object($var);
  810.     }
  811.     public function getName() {
  812.         return "slivki_extension";
  813.     }
  814.     public function getSaleShortDescription(Sale $sale) {
  815.         $saleDescriptions $sale->getDescriptions();
  816.         if (!$saleDescriptions || $saleDescriptions->count() == 0) {
  817.             return '';
  818.         }
  819.         $description $sale->getDescriptions()->first()->getDescription();
  820.         $crawler = new Crawler();
  821.         $crawler->addHtmlContent($description);
  822.         $pList $crawler->filter('p');
  823.         $i 0;
  824.         $shortDescription '';
  825.         foreach ($pList as $domElement) {
  826.             $p htmlentities($domElement->textContentnull'utf-8');
  827.             $p trim(str_replace("&nbsp;"" "$p));
  828.             $p html_entity_decode($p);
  829.             if (strlen($p) > 0) {
  830.                 $i++;
  831.                 if($i == 2) {
  832.                     $shortDescription $p;
  833.                     break;
  834.                 }
  835.             }
  836.         }
  837.         $shortDescription strip_tags($shortDescription);
  838.         return $shortDescription;
  839.     }
  840.     public function getSupplierOfferPhotoBlockByOfferID(Environment $twig$offerID) {
  841.         $perPage 20;
  842.         $mediaList $this->cacheService->getMediaList($offerID,OfferSupplierPhotoMedia::TYPE00$perPage);
  843.         if (empty($mediaList)) {
  844.             return '';
  845.         }
  846.         $data = [
  847.             'offerID' => $offerID,
  848.             'supplierOfferPhotoList' => $mediaList
  849.         ];
  850.         $data['supplierOfferPhotoList'] = array_slice($data['supplierOfferPhotoList'], 020);
  851.         return $twig->render('Slivki/comments/offer_supplier_photo_block.html.twig'$data);
  852.     }
  853.     public function getUserCommentsMediaBlockByEntityID(Environment $twig$entityID$entityType) {
  854.         $data['commentAndMediaList'] = [];
  855.         switch ($entityType) {
  856.             case 'category':
  857.                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaListByCategoryID($entityID);
  858.                 break;
  859.             case 'offer':
  860.                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaListByOfferID($entityID);
  861.                 break;
  862.             case 'all':
  863.                 $data['commentAndMediaList'] = $this->entityManager->getRepository(Media::class)->getOfferCommentMediaList();
  864.                 break;
  865.         }
  866.         $data['entityID'] = $entityID;
  867.         $data['entityType'] = $entityType;
  868.         if(empty($data['commentAndMediaList'])) {
  869.             return '';
  870.         }
  871.         $html $twig->render('Slivki/comments/media_block.html.twig'$data);
  872.         return $html;
  873.     }
  874.     public function getEntityRatingWithCount($entityType$entityID$dateFrom false$dateTo false) {
  875.         return $this->entityManager->getRepository(Comment::class)->getEntityRatingWithCount($entityType$entityID$dateFrom$dateTo);
  876.     }
  877.     public function getCompaniesRatingBlock(Environment $twig$categoryID$isMobile false) {
  878.         $type $isMobile TextCacheService::COMPANIES_RATING_MOBILE_TYPE TextCacheService::COMPANIES_RATING_TYPE;
  879.         $html $this->textCacheService->getText($categoryID$type);
  880.         if (!$html || $html == '') { //TODO: remove
  881.             $softCache = new SoftCache(OfferRepository::CACHE_NAME);
  882.             $mobileCacheName $isMobile 'mobile-' '';
  883.             $html $softCache->get('company-rating-data-' '-' $mobileCacheName $categoryID);
  884.         }
  885.         return $html $html '';
  886.     }
  887.     public function getMailingCampaignEntityPositionByEntityID($mailingCampaignID$entityID$entityType) {
  888.         $mailingCampaign $this->entityManager->getRepository(MailingCampaign::class)->find($mailingCampaignID);
  889.         return $mailingCampaign->getEntityPositionByEntityID($entityID$entityType);
  890.     }
  891.     public function getActiveCityList() {
  892.         return $this->entityManager->getRepository(City::class)->getActiveCitiesCached();
  893.     }
  894.     public function getActiveSortedCityList() {
  895.         return $this->entityManager->getRepository(City::class)->getActiveSortedCitiesCached();
  896.     }
  897.     public function getCurrentCity() {
  898.         return $this->entityManager->getRepository(City::class)->findCached($this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID));
  899.     }
  900.     public function setSeenMicrophoneTooltip(User $user) {
  901.         if (!$user->isSeenMicrophoneTooltip()) {
  902.             $user $this->entityManager->merge($user);
  903.             $user->setSeenMicrophoneTooltip();
  904.             $this->entityManager->flush($user);
  905.         }
  906.     }
  907.     public function getFlierProductCategories(Environment $twig) {
  908.         $dql "select category from Slivki:ProductCategory category where category.parents is empty order by category.name ASC";
  909.         $categories $this->entityManager->createQuery($dql)->getResult();
  910.         return $twig->render('Slivki/admin/sales/products/category_list.html.twig', ['categories' => $categories]);
  911.     }
  912.     public function getFlierProductSubCategories(Environment $twig$categoryID) {
  913.         $categories $this->entityManager->getRepository(ProductCategory::class)->find($categoryID);
  914.         $subCategories $categories->getSubCategories();
  915.         return  $twig->render('Slivki/admin/sales/products/sub_category_list.html.twig', ['categories' => $subCategories]);
  916.     }
  917.     public function getIPLocationData() {
  918.         $defaultLocation = [53.90225027.561889];
  919.         return $defaultLocation;
  920.         $data $this->entityManager->getRepository(City::class)->getIPLocationData($this->request);
  921.         if (!$data) {
  922.             return $defaultLocation;
  923.         }
  924.         return [$data['latitude'], $data['longitude']];
  925.     }
  926.     public function isInDefaultCity() {
  927.         return City::DEFAULT_CITY_ID == $this->entityManager->getRepository(City::class)->getCityIDByGeoIP($this->request);
  928.     }
  929.     public function isTireDirector($userID) {
  930.         return $this->entityManager->getRepository(Director::class)->isTireDirector($userID);
  931.     }
  932.     public function getCurrentCityURL() {
  933.         $cityID $this->request->getSession()->get(City::CITY_ID_SESSION_KEYCity::DEFAULT_CITY_ID);
  934.         if ($cityID == City::DEFAULT_CITY_ID) {
  935.             return '/';
  936.         }
  937.         return $this->entityManager->getRepository(Seo::class)->getCityURL($cityID);
  938.     }
  939.     public function showMyPromocodesMenuItem(User $user) {
  940.         $userRepository $this->entityManager->getRepository(User::class);
  941.         $lastBuyDate $userRepository->getLastBuyDate($user);
  942.         if (!$lastBuyDate) {
  943.             return false;
  944.         }
  945.         return time() - $lastBuyDate->format('U') < 30 24 3600;
  946.     }
  947.     public function getFooter(Environment $twig): string
  948.     {
  949.         $mobile $this->isMobileDevice();
  950.         $footerVersion rand(01);
  951.         $cacheKey 'footer-4-' $this->getCurrentCity()->getID() . '-'  . ($mobile '-mobile' '') . '-' $footerVersion;
  952.         $softCache = new SoftCache('');
  953.         $footer $softCache->getDataWithLock($cacheKey);
  954.         if (!$footer) {
  955.             $view sprintf(
  956.                 'Slivki%s/footer%s.html.twig',
  957.                 $this->parameterBag->get('regional_template_path'),
  958.                 $mobile '_mobile' '',
  959.             );
  960.             $footer $twig->render($view, ['footerVersion' => $footerVersion]);
  961.             $data = ['data' => $footer'expDate' => time() + 60 60];
  962.             $softCache->set($cacheKey$data0);
  963.         }
  964.         return $footer;
  965.     }
  966.     public function getSaleCategoriesSortedBySaleVisits() {
  967.         return $this->entityManager->getRepository(Category::class)->getSaleCategoriesSortedBySaleVisits();
  968.     }
  969.     public function addLazyAndLightboxImagesInDescription($description) {
  970.         if (trim($description) == '') {
  971.             return '';
  972.         }
  973.         $html = new Crawler();
  974.         $html->addHtmlContent($description);
  975.         $nodeList $html->filter('img');
  976.         if (!empty($nodeList)) {
  977.             $nodeList->each(function (Crawler $node) {
  978.                 $nodeElem $node->getNode(0);
  979.                 $source $nodeElem->getAttribute('src');
  980.                 $dataOriginal $nodeElem->getAttribute('data-original');
  981.                 if ($source and !$dataOriginal) {
  982.                     $nodeElem->setAttribute('src''/common-img/d.gif');
  983.                     $nodeElem->setAttribute('data-original'$source);
  984.                     $nodeElem->setAttribute('class''sale-lazy-spin');
  985.                     $parentElem $node->parents()->first()->getNode(0);
  986.                     $ratio $nodeElem->getAttribute('data-ratio');
  987.                     if ($ratio != '') {
  988.                         $newParentNode = new \DOMElement('div');
  989.                         $parentElem->replaceChild($newParentNode$nodeElem);
  990.                         $newParentNode->setAttribute('class''sale-lazy-wrap');
  991.                         $width $nodeElem->getAttribute('width');
  992.                         $style $nodeElem->getAttribute('style');
  993.                         $newParentNode->setAttribute('style''max-width:' $width'px;' $style);
  994.                         $nodeForPadding =  new \DOMElement('div');
  995.                         $newParentNode->appendChild($nodeForPadding);
  996.                         $nodeForPadding->setAttribute('style''padding-bottom:' $ratio'%');
  997.                         $newParentNode->appendChild($nodeElem);
  998.                     }
  999.                 }
  1000.             });
  1001.         }
  1002.         if (self::isMobileDevice()) {
  1003.             $nodeList $html->filter('iframe');
  1004.             if (!empty($nodeList)) {
  1005.                 $nodeList->each(function (Crawler $node) {
  1006.                     $nodeElem $node->getNode(0);
  1007.                     $source $nodeElem->getAttribute('src');
  1008.                     if (strpos($source'youtube') !== false) {
  1009.                         $parentElem $node->parents()->first()->getNode(0);
  1010.                         $newParentNode = new \DOMElement('div');
  1011.                         $parentElem->replaceChild($newParentNode$nodeElem);
  1012.                         $newParentNode->setAttribute('class''embed-responsive embed-responsive-16by9');
  1013.                         $nodeElem->setAttribute('class''embed-responsive-item');
  1014.                         $newParentNode->appendChild($nodeElem);
  1015.                     }
  1016.                 });
  1017.             }
  1018.         }
  1019.         $result str_replace('<body>'''$html->html());
  1020.         $result str_replace('</body>'''$result);
  1021.         return $result;
  1022.     }
  1023.     public function getMedia($entityID$type) {
  1024.         $mediaList $this->entityManager->getRepository(Media::class)->getMedia($entityID$type);
  1025.         return $mediaList $mediaList[0] : null;
  1026.     }
  1027.     public function logWrite($data) {
  1028.         Logger::instance('TWIG LOG WRITER')->info(print_r($datatrue));
  1029.     }
  1030.     public function getManagerPhoneNumber($offset 0) {
  1031.         switch ($this->getCurrentCity()->getID()) {
  1032.             case 5:
  1033.                 return '+375 29 380 03 33';
  1034.             case 2:
  1035.                 return '+375 29 678 53 32';
  1036.             default:
  1037.                 return '+375 29 508 44 44';
  1038.         }
  1039.     }
  1040.     public function calcDeliveryPriceOffer(
  1041.         $extension,
  1042.         $pickupDeliveryType,
  1043.         $regularPrice,
  1044.         $priceOffer,
  1045.         ?OfferExtensionVariant $extensionVariant
  1046.     )
  1047.     {
  1048.         return PriceDeliveryType::calcDeliveryPickupPrice(
  1049.             $extension,
  1050.             $pickupDeliveryType,
  1051.             $regularPrice,
  1052.             $priceOffer,
  1053.             $extensionVariant
  1054.         );
  1055.     }
  1056.     public function getSocialProviderLoginUrl($socialNetwork$goto) {
  1057.         $className 'Slivki\Util\OAuth2Client\Provider\\' ucfirst($socialNetwork) . 'Client';
  1058.         /** @var AbstractOAuth2Client $oAuthProvider */
  1059.         $oAuthProvider = new $className();
  1060.         return $oAuthProvider->getLoginUrl($goto);
  1061.     }
  1062.     public function isProductFastDelivery($director): bool
  1063.     {
  1064.         if (null === $director) {
  1065.             return false;
  1066.         }
  1067.         $offers $director->getOffers();
  1068.         /** @var ProductFastDeliveryRepository $deliveryFastRepository */
  1069.         $deliveryFastRepository $this->entityManager->getRepository(ProductFastDelivery::class);
  1070.         /** @var Offer $offerItem */
  1071.         foreach ($offers as $offerItem) {
  1072.             if ($offerItem->isActive()) {
  1073.                 $times $deliveryFastRepository->getFastDeliveryProductsByOffer($offerItem);
  1074.                 if ($times) {
  1075.                     return true;
  1076.                 }
  1077.             }
  1078.         }
  1079.         return false;
  1080.     }
  1081.     public function calcDishDiscount($regularPrice$offerPrice) {
  1082.         $offerPrice = (float)$offerPrice;
  1083.         $regularPrice = (float)$regularPrice;
  1084.         if ($regularPrice == 0) {
  1085.             return 0;
  1086.         }
  1087.         return \round(100 - ($offerPrice $regularPrice 100));
  1088.     }
  1089.     public function getRTBHouseUID(User $user null) {
  1090.         return $this->RTBHouseService->getUID($user);
  1091.     }
  1092.     public function getVimeoEmbedPreview($videoId)
  1093.     {
  1094.         $config $this->videoConfigService->config($videoId);
  1095.         if (isset($config['video']['thumbs'])
  1096.             && \is_array($config['video']['thumbs'])
  1097.             && \count($config['video']['thumbs']) > 0
  1098.         ) {
  1099.             return \reset($config['video']['thumbs']);
  1100.         }
  1101.         return '';
  1102.     }
  1103.     public function getUserBalanceCodesCount(User $user$cityID) {
  1104.         return $this->entityManager->getRepository(User::class)->getUserBalanceCodesCount($user$cityID);
  1105.     }
  1106.     public function showAppInviteModal(User $user null) : bool {
  1107.         if (!$user) {
  1108.             return true;
  1109.         }
  1110.         $sql 'select max(created_on) from offer_order'
  1111.             .' where status > 0 and device_type = ' SiteController::DEVICE_TYPE_MOBILE_APP
  1112.             ' and user_id = ' $user->getID();
  1113.         $userLastAppPurchaseDate $this->entityManager->getConnection()->executeQuery($sql)->fetchColumn();
  1114.         if (!$userLastAppPurchaseDate) {
  1115.             return true;
  1116.         }
  1117.         return (new \DateTime($userLastAppPurchaseDate) < (new \DateTime())->modify('-1 month'));
  1118.     }
  1119. }