src/Twig/SlivkiTwigExtension.php line 246

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