src/Twig/SlivkiTwigExtension.php line 1004

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