src/WebBundle/Twig/AppExtension.php line 94

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Twig;
  3. use DateTime;
  4. use Doctrine\DBAL\DBALException;
  5. use Exception;
  6. use FlexApp\Constant\TimeConstant;
  7. use FlexApp\Repository\BoolDBSettingRepository;
  8. use FlexApp\Repository\ChatBMessageRepository;
  9. use FlexApp\Repository\ChatBRepository;
  10. use FlexApp\Repository\WidgetRepository;
  11. use FlexApp\Service\CalendarService;
  12. use FlexApp\Service\JWTGenerator;
  13. use Imagick;
  14. use ImagickException;
  15. use Import1CBundle\Helper\v3\BiConst;
  16. use Import1CBundle\Helper\v3\TranslitNameHelper;
  17. use Memcache;
  18. use ReflectionClass;
  19. use Symfony\Component\DependencyInjection\ContainerInterface;
  20. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  21. use Symfony\Contracts\Translation\TranslatorInterface;
  22. use Twig\Extension\AbstractExtension;
  23. use Twig\Extension\GlobalsInterface;
  24. use Twig\TwigFilter;
  25. use Twig\TwigFunction;
  26. use WebBundle\Entity\Article;
  27. use WebBundle\Entity\ArticlePriceDiscount;
  28. use WebBundle\Entity\BuyOrder;
  29. use WebBundle\Entity\BuyOrderArticle;
  30. use WebBundle\Entity\Factory;
  31. use WebBundle\Entity\ListStyle;
  32. use WebBundle\Enum\BuyOrderStatusEnum;
  33. use WebBundle\Enum\CountryNumberEnum;
  34. use WebBundle\Helper\App;
  35. use WebBundle\Helper\CalendarHelper;
  36. use WebBundle\Helper\ConversionHelper;
  37. use WebBundle\Helper\CookieHelper;
  38. use WebBundle\Helper\HumanDataHelper;
  39. use WebBundle\Helper\LocaleHelper;
  40. use WebBundle\Helper\CurrencyRateHelper;
  41. use WebBundle\Helper\OrderHelper;
  42. use WebBundle\Helper\OrderItemHelper;
  43. use WebBundle\Helper\PathHelper;
  44. use WebBundle\Helper\SliderHelper;
  45. use WebBundle\Helper\StrHelper;
  46. use WebBundle\Helper\TranslitHelper;
  47. use WebBundle\Helper\TwigTe;
  48. use WebBundle\Helper\UserHelper;
  49. class AppExtension extends AbstractExtension implements GlobalsInterface
  50. {
  51.     /** @required */
  52.     public ChatBRepository $chatBRepository;
  53.     /** @required */
  54.     public ChatBMessageRepository $chatBMessageRepository;
  55.     /** @required */
  56.     public BoolDBSettingRepository $boolDBSettingRepository;
  57.     /** @required */
  58.     public WidgetRepository $widgetRepository;
  59.     /** @required */
  60.     public JWTGenerator $jwtGenerator;
  61.     private ContainerInterface $container;
  62.     private TranslatorInterface $translator;
  63.     private UrlGeneratorInterface $urlGenerator;
  64.     public function __construct(
  65.         ContainerInterface $container,
  66.         TranslatorInterface $translator,
  67.         UrlGeneratorInterface $urlGenerator
  68.     ) {
  69.         $this->container $container;
  70.         $this->translator $translator;
  71.         $this->urlGenerator $urlGenerator;
  72.     }
  73.     public function getName(): string
  74.     {
  75.         return 'app_extension';
  76.     }
  77.     /**
  78.      * Регистрируем глобальные переменные
  79.      * @throws Exception
  80.      */
  81.     public function getGlobals(): array
  82.     {
  83.         return [
  84.             'fullDomain' => App::getParameter('full_domain'),
  85.             'userSession' => $_COOKIE,
  86.             'te' => TwigTe::that(),
  87.             'csrf_token' => App::getContainer()->get('security.csrf.token_manager')->getToken('authenticate')->getValue(),
  88.             'portalWsServer' => $this->container->getParameter('portal_ws_server'),
  89.             'token' => UserHelper::getInstance()->getToken(),
  90.             'centrifugoConnectionUrl' => $this->container->getParameter('centrifugo.connection_url'),
  91.         ];
  92.     }
  93.     public function getClassName($entity): string
  94.     {
  95.         return (new ReflectionClass($entity))->getShortName();
  96.     }
  97.     public function getFunctions(): array
  98.     {
  99.         return [
  100.             'className' => new TwigFunction('className', [$this'getClassName']),
  101.             'measureGb' => new TwigFunction('measureGb', [$this'measureGb']),
  102.             'currency' => new TwigFunction('currency', [$this'currency']),
  103.             'userLocale' => new TwigFunction('userLocale', [$this'userLocale']),
  104.             'orderItemTime' => new TwigFunction('orderItemTime', [$this'orderItemTime']),
  105.             'dateMask' => new TwigFunction('dateMask', [$this'dateMask']),
  106.             'userCurrency' => new TwigFunction('userCurrency', [$this'userCurrency']),
  107.             'userGA' => new TwigFunction('userGA', [$this'userGA']),
  108.             'userCountry' => new TwigFunction('userCountry', [$this'userCountry']),
  109.             'userMeasure' => new TwigFunction('userMeasure', [$this'userMeasure']),
  110.             'prMin' => new TwigFunction('prMin', [$this'prMin']),
  111.             'price' => new TwigFunction('price', [$this'price']),
  112.             'priceDiscount' => new TwigFunction('priceDiscount', [$this'priceDiscount']),
  113.             'typeTime' => new TwigFunction('typeTime', [$this'typeTime']),
  114.             'pathGenerate' => new TwigFunction('pathGenerate', [$this'pathGenerate']),
  115.             'timestamp' => new TwigFunction('timestamp', [$this'timestamp']),
  116.             'getCurLocale' => new TwigFunction('getCurLocale', [$this'getCurLocale']),
  117.             'footerLinks' => new TwigFunction('footerLinks', [$this'footerLinks']),
  118.             'curLimit' => new TwigFunction('curLimit', [$this'curLimit']),
  119.             'curLimitEx' => new TwigFunction('curLimitEx', [$this'curLimitEx']),
  120.             'curLimitVal' => new TwigFunction('curLimitVal', [$this'curLimitVal']),
  121.             'getCoords' => new TwigFunction('getCoords', [$this'getCoords']),
  122.             'getInteriorHead' => new TwigFunction('getInteriorHead', [$this'getInteriorHead']),
  123.             'show_attributes' => new TwigFunction('show_attributes', [$this'showAttributes']),
  124.             'wrapCents' => new TwigFunction('wrapCents', [$this'wrapCents']),
  125.             'show_style_attributes' => new TwigFunction('show_style_attributes', [$this'showStyleAttributes']),
  126.             'setides' => new TwigFunction('setides', [$this'setIdes']),
  127.             'isLogged' => new TwigFunction('isLogged', [$this'isLogged']),
  128.             'humanData' => new TwigFunction('humanData', [$this'humanData']),
  129.             'isEmployee' => new TwigFunction('isEmployee', [$this'isEmployee']),
  130.             'humanSampleType' => new TwigFunction('humanSampleType', [$this'humanSampleType']),
  131.             'SampleFormat' => new TwigFunction('SampleFormat', [$this'SampleFormat']),
  132.             'isWithoutVATPrice' => new TwigFunction('isWithoutVATPrice', [$this'isWithoutVATPrice']),
  133.             'includeVATAlways' => new TwigFunction('includeVATAlways', [$this'includeVATAlways']),
  134.             'baseProps' => new TwigFunction('baseProps', [$this'baseProps']),
  135.             'VatRequiredState' => new TwigFunction('VatRequiredState', [$this'vatRequiredState']),
  136.             'OrderPercent' => new TwigFunction('OrderPercent', [$this'orderPercent']),
  137.             'getPercent' => new TwigFunction('getPercent', [$this'getPercent']),
  138.             'sampleFormat' => new TwigFunction('sampleFormat', [$this'sampleFormat']),
  139.             'readyCreate' => new TwigFunction('readyCreate', [$this'readyCreate']),
  140.             'checkForSend' => new TwigFunction('checkForSend', [$this'checkForSend']),
  141.             'orderSum' => new TwigFunction('orderSum', [$this'orderSum']),
  142.             'availabilityItemOrder' => new TwigFunction('availabilityItemOrder', [$this'availabilityItemOrder']),
  143.             'asVat' => new TwigFunction('asVat', [$this'asVat']),
  144.             'homeCountryVat' => new TwigFunction('homeCountryVat', [$this'homeCountryVat']),
  145.             'deliveryWVat' => new TwigFunction('deliveryWVat', [$this'deliveryWVat']),
  146.             'paymentPercent' => new TwigFunction('paymentPercent', [$this'paymentPercent']),
  147.             'orderParams' => new TwigFunction('orderParams', [$this'orderParams']),
  148.             'vatFactor' => new TwigFunction('vatFactor', [$this'vatFactor']),
  149.             'isHoliday' => new TwigFunction('isHoliday', [$this'isHoliday']),
  150.             'totalSum' => new TwigFunction('totalSum', [$this'totalSum']),
  151.             'statePaymentButton' => new TwigFunction('statePaymentButton', [$this'statePaymentButton']),
  152.             'onlySamples' => new TwigFunction('onlySamples', [$this'onlySamples']),
  153.             'noVat' => new TwigFunction('noVat', [$this'noVat']),
  154.             'cmToInch' => new TwigFunction('cmToInch', [$this'cmToInch']),
  155.             'resolverScriptSize' => new TwigFunction('resolverScriptSize', [$this'resolverScriptSize']),
  156.             'getUnreadCount' => new TwigFunction('getUnreadCount', [$this'getUnreadCount']),
  157.             'getJwt' => new TwigFunction('getJwt', [$this'getJwt']),
  158.             'getUserChannel' => new TwigFunction('getUserChannel', [$this'getUserChannel']),
  159.             'OrderVatText' => new TwigFunction('OrderVatText', [$this'orderVatText']),
  160.             'OrderMsg' => new TwigFunction('OrderMsg', [$this'orderMsg']),
  161.             'orderStatusAliasByStatusId' => new TwigFunction('orderStatusAliasByStatusId', [$this'orderStatusAliasByStatusId']),
  162.             'assetAdm' => new TwigFunction('assetAdm', function ($link) {
  163.                 $asset = !App::isGeneral() ? time() : App::getParameter('assets.version.adm');
  164.                 return "{$link}?{$asset}";
  165.             }),
  166.             'useRTWidget' => new TwigFunction('useRTWidget', [$this'useRTWidget']),
  167.             'getWidgetId' => new TwigFunction('getWidgetId', [$this'getWidgetId']),
  168.             'getUrlForPaymentByVisa' => new TwigFunction('getUrlForPaymentByVisa', [$this'getUrlForPaymentByVisa']),
  169.             'getUrlForPaymentByAmex' => new TwigFunction('getUrlForPaymentByAmex', [$this'getUrlForPaymentByAmex']),
  170.             'formatPriceWithCurrency' => new TwigFunction('formatPriceWithCurrency', [$this'formatPriceWithCurrency'], ['is_safe' => ['html']]),
  171.         ];
  172.     }
  173.     public function getFilters(): array
  174.     {
  175.         return [
  176.             new TwigFilter('emphasis', [$this'emphasisFilter']),
  177.             new TwigFilter('q_change', [$this'qChangeFilter']),
  178.             new TwigFilter('url_clear', [$this'urlClearFilter']),
  179.             new TwigFilter('preg_replace', [$this'pReplaceFilter']),
  180.             new TwigFilter('data_last', [$this'dataLastFilter']),
  181.             new TwigFilter('slice_word', [$this'cutTextForWords']),
  182.             new TwigFilter('insertHolidays', [$this'insertHolidays']),
  183.             new TwigFilter('convert_text', [$this'convertText']),
  184.             new TwigFilter('friendly_date', [$this'friendlyDate']),
  185.             new TwigFilter('caseString', [$this'getCase']),
  186.             new TwigFilter('separator_word', [$this'separatorWord']),
  187.             new TwigFilter('u_first', [$this'uFirst']),
  188.             new TwigFilter('l_first', [$this'lFirst']),
  189.             new TwigFilter('u_print', [$this'uPrint']),
  190.             new TwigFilter('strspaceless', [$this'strSpaceless']),
  191.             new TwigFilter('InteriorSizeTiny', [$this'interiorSizeTiny']),
  192.             new TwigFilter('path_collection', [$this'pathCollection']),
  193.             new TwigFilter('actual_name', [$this'actualName']),
  194.             new TwigFilter('less_content', [$this'lessContent']),
  195.             new TwigFilter('convertDate', [$this'convertDate']),
  196.             new TwigFilter('transform', [$this'transform']),
  197.             new TwigFilter('replace_umlaut', [$this'replaceUmlautChar']),
  198.             new TwigFilter('decodeHtml', [$this'decodeHtml']),
  199.             new TwigFilter('strPos', [$this'strPos']),
  200.             new TwigFilter('getFractPartLength', [$this'getFractPartLength']),
  201.             new TwigFilter('short_fio', [$this'getShortFio']),
  202.             new TwigFilter('transLit', [$this'transLit']),
  203.             new TwigFilter('makeThumbnail', [$this'makeThumbnail']),
  204.             new TwigFilter('prime', [$this'prime']),
  205.             new TwigFilter('mb_strlen', [$this'mbStrlen']),
  206.             new TwigFilter('setDataHistoryOrder', [$this'setDataHistoryOrder']),
  207.             new TwigFilter('convertToHours', [$this'convertToHours']),
  208.             new TwigFilter('price', [$this'price']),
  209.             new TwigFilter('priceMq', [$this'priceMq']),
  210.             new TwigFilter('measure', [$this'measure']),
  211.             new TwigFilter('currency', [$this'currency']),
  212.             new TwigFilter('convertFt', [$this'convertFt']),
  213.             new TwigFilter('convertSqFt', [$this'convertSqFt']),
  214.             new TwigFilter('convertKgLb', [$this'convertKgLb']),
  215.             new TwigFilter('convertPrice', [$this'convertPrice']),
  216.             new TwigFilter('packagingCount', [$this'packagingCount']),
  217.             new TwigFilter('pallet', [$this'pallet']),
  218.             new TwigFilter('amount', [$this'amount']),
  219.             new TwigFilter('weight', [$this'weight']),
  220.             new TwigFilter('weightLabel', [$this'weightLabel']),
  221.             new TwigFilter('measureGb', [$this'measureGb']),
  222.             new TwigFilter('convertInch', [$this'convertInch']),
  223.             new TwigFilter('replace_symbols_title', [$this'replaceSymbolsTitleFilter']),
  224.             new TwigFilter('floatSing', [$this'floatSing']),
  225.             new TwigFilter('bcdiv', [$this'bcdiv']),
  226.             new TwigFilter('floatSingDec', [$this'floatSingDec']),
  227.             new TwigFilter('removeDec', [$this'removeDec']),
  228.             new TwigFilter('pad', [$this'pad']),
  229.             new TwigFilter('HSCCard', [$this'HSCCard']),
  230.             new TwigFilter('symbolCyrillicUnderline', [$this'symbolCyrillicUnderline']),
  231.             new TwigFilter('lenThanSomeSymbol', [$this'lenThanSomeSymbol']),
  232.             new TwigFilter('declension', [$this'declension']),
  233.         ];
  234.     }
  235.     /**
  236.      * передаём перевод для "артикул" с нужным окончанием, в зависимости от кол-ва и языка
  237.      *
  238.      * @param $num
  239.      * @param $expressions
  240.      * @param $lang
  241.      *
  242.      * @return mixed|null
  243.      */
  244.     public function declension($num$expressions$lang)
  245.     {
  246.         $result null;
  247.         $count null;
  248.         $count $num 100;
  249.         if (== $num) {
  250.             $result $expressions['0'];
  251.         } elseif ('ru' != $lang && 'pl' != $lang) {
  252.             $result $expressions['1'];
  253.         } elseif ($count >= && $count <= 20) {
  254.             $result $expressions['2'];
  255.         } else {
  256.             $count $count 10;
  257.             if (== $count && 'ru' == $lang) {
  258.                 $result $expressions['0'];
  259.             } elseif ($count >= && $count <= 4) {
  260.                 $result $expressions['1'];
  261.             } else {
  262.                 $result $expressions['2'];
  263.             }
  264.         }
  265.         return $result;
  266.     }
  267.     /**
  268.      * @param $str
  269.      *
  270.      * @return mixed
  271.      */
  272.     public function HSCCard($str)
  273.     {
  274.         return htmlspecialchars($strENT_COMPAT ENT_HTML401'UTF-8');
  275.     }
  276.     /**
  277.      * записать в кеш список ид артикулов распродажи
  278.      *
  279.      * @param $ides
  280.      *
  281.      * @return string
  282.      */
  283.     public function setIdes($ides)
  284.     {
  285.         $memkey 'memkey-' UserHelper::getInstance()->getToken();
  286.         $memcache = new Memcache();
  287.         $memcache->connect(App::getParameter('memcache_host'), App::getParameter('memcache_port'));
  288.         if ($ides) {
  289.             $memcache->add($memkey$idesfalse, (int) TimeConstant::HOUR);
  290.         } else {
  291.             $memcache->delete($memkey);
  292.         }
  293.         return $memkey;
  294.     }
  295.     /**
  296.      * @return bool
  297.      *
  298.      * @throws Exception
  299.      */
  300.     public function isLogged()
  301.     {
  302.         return (bool) App::getCurUser();
  303.     }
  304.     public function pad($str$padLength$sign)
  305.     {
  306.         return str_pad($str$padLength$signSTR_PAD_LEFT);
  307.     }
  308.     public function mbStrlen($content)
  309.     {
  310.         return mb_strlen($content'utf-8');
  311.     }
  312.     public function transLit($str)
  313.     {
  314.         return TranslitHelper::convert($strLocaleHelper::getDefault());
  315.     }
  316.     /**
  317.      * Отчищает строку от лишних знаков для адреса url
  318.      *
  319.      * @param string $string
  320.      * @param bool $flag
  321.      *
  322.      * @return string
  323.      */
  324.     public function urlClearFilter($string$flag true)
  325.     {
  326.         if ($flag) {
  327.             $s = ['('')''&''/''\\''`''\'''%'',''.''#''?''"'];
  328.         } else {
  329.             $s = ['('')''/''\\''`''\'''%'',''.''#''?''"'];
  330.         }
  331.         $string str_replace($s''$string);
  332.         return preg_replace('#[\s]#i''-'trim($string));
  333.     }
  334.     /**
  335.      * Отчищает строку от лишних знаков для адреса url
  336.      *
  337.      * @param string $string
  338.      *
  339.      * @return string
  340.      */
  341.     public function qChangeFilter($string)
  342.     {
  343.         return TranslitNameHelper::replacePrime($stringfalse);
  344.     }
  345.     /**
  346.      * Для пользовательских регулярных выражений в шаблонах
  347.      *
  348.      * @param string $string
  349.      * @param string|array $pattern строка или массив регулярных выражений
  350.      * @param string|array $replacement массив замены
  351.      *
  352.      * @return string
  353.      */
  354.     public function pReplaceFilter($string$pattern$replacement)
  355.     {
  356.         return preg_replace($pattern$replacement$string);
  357.     }
  358.     /**
  359.      * Меняет большую гласную букву на маленькую с ударением
  360.      *
  361.      * @param string $str преобразуемая строка
  362.      *
  363.      * @return string
  364.      */
  365.     public function emphasisFilter($str)
  366.     {
  367.         $str preg_replace('#\s+#isUu'' '$str);
  368.         $words explode(' '$str);
  369.         $newWords = [];
  370.         foreach ($words as $word) {
  371.             preg_match_all('#[А-Я|A-Z]#u'$word$matches);
  372.             $ch_str '';
  373.             foreach (array_reverse($matches[0]) as $match) {
  374.                 if (
  375.                     in_array($match, [
  376.                     'a',
  377.                     'e',
  378.                     'i',
  379.                     'o',
  380.                     'u',
  381.                     'A',
  382.                     'E',
  383.                     'I',
  384.                     'O',
  385.                     'U',
  386.                     'а',
  387.                     'е',
  388.                     'ё',
  389.                     'и',
  390.                     'о',
  391.                     'у',
  392.                     'э',
  393.                     'ю',
  394.                     'я',
  395.                     'А',
  396.                     'Е',
  397.                     'Ё',
  398.                     'И',
  399.                     'О',
  400.                     'У',
  401.                     'Э',
  402.                     'Ю',
  403.                     'Я',
  404.                     ])
  405.                 ) {
  406.                     $ch_str str_replace($matchmb_convert_case($matchMB_CASE_LOWER'UTF-8') . '&#x301;'$word);
  407.                     break;
  408.                 }
  409.             }
  410.             if (empty($ch_str)) {
  411.                 $ch_str $word;
  412.             }
  413.             $newWords[] = $ch_str;
  414.         }
  415.         return mb_convert_case(implode(' '$newWords), MB_CASE_LOWER'UTF-8');
  416.     }
  417.     /**
  418.      * @param DateTime $date
  419.      *
  420.      * @return string
  421.      */
  422.     public static function dataLastFilter($date)
  423.     {
  424.         $now date('d.m.y');
  425.         $yesterday date('d.m.y'strtotime(date('Y-m-d')) - 3600 24);
  426.         switch ($date) {
  427.             case $date == $now:
  428.                 $result 'main_menu_today';
  429.                 break;
  430.             case $date == $yesterday:
  431.                 $result 'main_menu_yesterday';
  432.                 break;
  433.             default:
  434.                 $result false;
  435.                 break;
  436.         }
  437.         return $result;
  438.     }
  439.     /**
  440.      * @param string $date
  441.      * @param string $p
  442.      *
  443.      * @return string
  444.      */
  445.     public static function convertDate($date$p)
  446.     {
  447.         return date($pstrtotime($date));
  448.     }
  449.     /**
  450.      * Функция обрезки текста по словам
  451.      *
  452.      * @param string $text - исходный текст
  453.      * @param int $length - максимальная длина получаемого текста
  454.      * @param bool $addDots
  455.      *
  456.      * @return string
  457.      */
  458.     public static function cutTextForWords($text$length$addDots false)
  459.     {
  460.         return StrHelper::cutText($text$length$addDots);
  461.     }
  462.     /**
  463.      * @param string $text
  464.      *
  465.      * @return string|string[]
  466.      *
  467.      * @throws Exception
  468.      */
  469.     public function insertHolidays(string $text)
  470.     {
  471.         // Получаем строки выходных и сокращенных дней только один раз
  472.         if (!isset($this->holidaysString)) {
  473.             $calendarService $this->container->get(CalendarService::class);
  474.             $this->holidaysString $calendarService->getHolidaysString(CalendarHelper::HOLIDAY_TYPE);
  475.         }
  476.         if (!isset($this->halfHolidaysString)) {
  477.             $calendarService $this->container->get(CalendarService::class);
  478.             $this->halfHolidaysString $calendarService->getHolidaysString(CalendarHelper::HALF_HOLIDAY_TYPE);
  479.         }
  480.         $text str_replace('%holidays%'$this->holidaysString$text);
  481.         $text str_replace('%half-holidays%'$this->halfHolidaysString$text);
  482.         return $text;
  483.     }
  484.     /**
  485.      * Обработка текста перед выводом в блогах
  486.      *
  487.      * @param string $text - исходный текст
  488.      *
  489.      * @return string
  490.      */
  491.     public static function convertText($text)
  492.     {
  493.         $out str_replace([
  494.             'https://portal.treto.ru/portal.nsf/v0/',
  495.             'http://portal.treto.ru/portal.nsf/v0/',
  496.             'https://treto.ru/attach/v0/',
  497.             'http://treto.ru/attach/v0/',
  498.             '../v0',
  499.         ], 'https://te.remote.team/v0/'$text);
  500.         $out str_replace(['<iframe''</iframe>'], ['<span class="blog-video-outer-wrapper"><span class="blog-video-inner-wrapper"><iframe''</iframe></span></span>'], $out);
  501.         //<div class="blog-video-wrapper"></div>
  502.         //<p><br><iframe src="//www.youtube.com/embed/2TRNuSKglwc" width="854" height="510" frameborder="0"></iframe></p>
  503.         return $out;
  504.     }
  505.     /**
  506.      * @param DateTime $date
  507.      *
  508.      * @return string
  509.      */
  510.     public static function friendlyDate($date)
  511.     {
  512.         if (empty($date)) {
  513.             return null;
  514.         }
  515.         $now date('d.m.y');
  516.         if ($date->format('d.m.y') == $now) {
  517.             return $date->format('H:i');
  518.         } else {
  519.             return $date->format('d.m.y');
  520.         }
  521.     }
  522.     /**
  523.      * @param $num - число
  524.      * @param $words - массив падежей слова ([1], [2-4], [остальное])
  525.      *
  526.      * @return string
  527.      */
  528.     public static function getCase($num$words)
  529.     {
  530.         return TranslitHelper::getCase($num$words);
  531.     }
  532.     /**
  533.      * @param string $text
  534.      * @param int $length
  535.      *
  536.      * @return string
  537.      */
  538.     public static function separatorWord($text$length 20)
  539.     {
  540.         return wordwrap(str_replace(['~q~''?'], ['\'''&oslash;'], $text), $length"\n"1);
  541.     }
  542.     /**
  543.      * @param string $text
  544.      *
  545.      * @return string
  546.      */
  547.     public static function uFirst($text)
  548.     {
  549.         $text trim($text);
  550.         return mb_convert_case(mb_substr($text01'UTF-8'), MB_CASE_UPPER'UTF-8') . mb_convert_case(mb_substr($text1mb_strlen($text), 'UTF-8'), MB_CASE_LOWER'UTF-8');
  551.     }
  552.     /**
  553.      * @param string $text
  554.      *
  555.      * @return string
  556.      */
  557.     public static function lFirst($text)
  558.     {
  559.         return mb_convert_case(mb_substr($text01'UTF-8'), MB_CASE_LOWER'UTF-8') . mb_substr($text1mb_strlen($text), 'UTF-8');
  560.     }
  561.     /**
  562.      * @param string $text
  563.      *
  564.      * @return string
  565.      */
  566.     public static function uPrint($text)
  567.     {
  568.         return '<pre>' print_r($texttrue) . '</pre>';
  569.     }
  570.     public static function strSpaceless($value)
  571.     {
  572.         return preg_replace('/\s+/'''$value);
  573.     }
  574.     /**
  575.      * @param array $interior
  576.      * @param string $type
  577.      *
  578.      * @return int
  579.      */
  580.     public function interiorSizeTiny($interior$type 'x')
  581.     {
  582.         if ('x' == strtolower($type)) {
  583.             if ($interior['fileSizeZX'] && $interior['fileSizeZY']) {
  584.                 return $interior['fileSizeZX'];
  585.             }
  586.             if ($interior['fileSizeX'] && $interior['fileSizeY']) {
  587.                 return $interior['fileSizeX'];
  588.             }
  589.             if ($interior['fileSizeHDX'] && $interior['fileSizeHDY']) {
  590.                 return $interior['fileSizeHDX'];
  591.             }
  592.             if ($interior['fileSizeSHDX'] && $interior['fileSizeSHDY']) {
  593.                 return $interior['fileSizeSHDX'];
  594.             }
  595.         } elseif ('y' == strtolower($type)) {
  596.             if ($interior['fileSizeZX'] && $interior['fileSizeZY']) {
  597.                 return $interior['fileSizeZY'];
  598.             }
  599.             if ($interior['fileSizeX'] && $interior['fileSizeY']) {
  600.                 return $interior['fileSizeY'];
  601.             }
  602.             if ($interior['fileSizeHDX'] && $interior['fileSizeHDY']) {
  603.                 return $interior['fileSizeHDY'];
  604.             }
  605.             if ($interior['fileSizeSHDX'] && $interior['fileSizeSHDY']) {
  606.                 return $interior['fileSizeSHDY'];
  607.             }
  608.         }
  609.         return 0;
  610.     }
  611.     /**
  612.      * Строит путь до папки коллекции
  613.      *
  614.      * @param $collection
  615.      *
  616.      * @return string
  617.      */
  618.     public function pathCollection($collection)
  619.     {
  620.         $path '';
  621.         if (BiConst::CHOICE_ADDRESS_URL) {
  622.             if (!empty($collection['factory']['url']) && !empty($collection['url'])) {
  623.                 $path PathHelper::getImgWebPath() .
  624.                     $collection['factory']['url'] . '/' $collection['url'] .
  625.                     '/' BiConst::PER_SITO '/';
  626.             }
  627.         } else {
  628.             if (!empty($collection['factory']['name']) && !empty($collection['name'])) {
  629.                 $path PathHelper::getImgWebPath() . rawurlencode(TranslitNameHelper::replacePrime($collection['factory']['name'], false)) . '/' rawurlencode(TranslitNameHelper::replacePrime($collection['name'], false)) .
  630.                     '/' BiConst::PER_SITO '/';
  631.             }
  632.         }
  633.         return $path;
  634.     }
  635.     public function prime($str)
  636.     {
  637.         return TranslitNameHelper::replacePrime($strfalse);
  638.     }
  639.     /**
  640.      * @param $data
  641.      *
  642.      * @return string
  643.      */
  644.     public function actualName($data)
  645.     {
  646.         if (is_array($data)) {
  647.             if (!empty($data['alternateName'])) {
  648.                 return $data['alternateName'];
  649.             } else {
  650.                 return $data['name'];
  651.             }
  652.         } else {
  653.             /* @var Factory $data */
  654.             return null != $data->getAlternateName() ? $data->getAlternateName() : $data->getName();
  655.         }
  656.     }
  657.     public function lessContent($text$length$lessText$moreText)
  658.     {
  659.         $text htmlspecialchars_decode($text);
  660.         if (mb_strlen(preg_replace('/<.*?>/'''$text), 'UTF-8') <= $length) {
  661.             return $text;
  662.         }
  663.         $totalLength 0;
  664.         $openTags = [];
  665.         $truncate '';
  666.         preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/'$text$tagsPREG_SET_ORDER);
  667.         foreach ($tags as $tag) {
  668.             if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s'$tag[2])) {
  669.                 if (preg_match('/<[\w]+[^>]*>/s'$tag[0])) {
  670.                     array_unshift($openTags$tag[2]);
  671.                 } else {
  672.                     if (preg_match('/<\/([\w]+)[^>]*>/s'$tag[0], $closeTag)) {
  673.                         $pos array_search($closeTag[1], $openTags);
  674.                         if (false !== $pos) {
  675.                             array_splice($openTags$pos1);
  676.                         }
  677.                     }
  678.                 }
  679.             }
  680.             $truncate .= $tag[1];
  681.             $contentLength mb_strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i'' '$tag[3]), 'UTF-8');
  682.             if ($contentLength $totalLength $length) {
  683.                 $left $length $totalLength;
  684.                 $entitiesLength 0;
  685.                 if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i'$tag[3], $entitiesPREG_OFFSET_CAPTURE)) {
  686.                     foreach ($entities[0] as $entity) {
  687.                         if ($entity[1] + $entitiesLength <= $left) {
  688.                             --$left;
  689.                             $entitiesLength += mb_strlen($entity[0], 'UTF-8');
  690.                         } else {
  691.                             break;
  692.                         }
  693.                     }
  694.                 }
  695.                 $truncate .= mb_substr($tag[3], 0$left $entitiesLength'UTF-8');
  696.                 break;
  697.             } else {
  698.                 $truncate .= $tag[3];
  699.                 $totalLength += $contentLength;
  700.             }
  701.             if ($totalLength >= $length) {
  702.                 break;
  703.             }
  704.         }
  705.         $truncate .= '...';
  706.         foreach ($openTags as $tag) {
  707.             $truncate .= '</' $tag '>';
  708.         }
  709.         return '<div class="content-less">' $truncate '</div>' .
  710.             '<div class="content-full">' $text '</div>' .
  711.             '<a class="content-more-link" rel="nofollow" data-action="open"' .
  712.             ' data-more-up="' $lessText '"' .
  713.             ' data-more-down="' $moreText '">' .
  714.             $moreText '</a>';
  715.     }
  716.     public function transform($text)
  717.     {
  718.         return TranslitNameHelper::replacePrime($textfalse);
  719.     }
  720.     public function replaceUmlautChar($text)
  721.     {
  722.         return StrHelper::replaceUmlautChar($text);
  723.     }
  724.     public function decodeHtml($str)
  725.     {
  726.         return htmlspecialchars_decode($str);
  727.     }
  728.     /**
  729.      * @param $str
  730.      * @param $needle
  731.      * @param int $offset
  732.      *
  733.      * @return bool|int
  734.      */
  735.     public function strPos($str$needle$offset 0)
  736.     {
  737.         return strpos($str$needle$offset);
  738.     }
  739.     /**
  740.      * Функция возврата количества символов в дробной части числа
  741.      *
  742.      * @param $str
  743.      *
  744.      * @return int
  745.      */
  746.     public function getFractPartLength($str)
  747.     {
  748.         $result 0;
  749.         $str str_replace(',''.'$str);
  750.         if (strpos($str'.')) {
  751.             $fractPart explode('.'$str);
  752.             $result strlen($fractPart[1]);
  753.         }
  754.         return $result;
  755.     }
  756.     /**
  757.      * @param $text
  758.      *
  759.      * @return string
  760.      */
  761.     public static function getShortFio($text)
  762.     {
  763.         $fio explode(' '$text);
  764.         $c count($fio);
  765.         if ($c 2) {
  766.             return $text;
  767.         }
  768.         //        mb_internal_encoding("UTF-8");
  769.         $newFio = [];
  770.         foreach ($fio as $key => $n) {
  771.             if ($key 0) {
  772.                 $n mb_substr($n01'UTF-8') . '.';
  773.             }
  774.             $newFio[] = $n;
  775.         }
  776.         return implode(' '$newFio);
  777.     }
  778.     /**
  779.      * @param $imagePath
  780.      *
  781.      * @return string
  782.      *
  783.      * @throws ImagickException
  784.      */
  785.     public function makeThumbnail($imagePath)
  786.     {
  787.         //try {
  788.         $whitelist = [
  789.             '127.0.0.1',
  790.             '::1',
  791.         ];
  792.         //$imageClearPath = htmlentities($imagePath);
  793.         $remoteAddr $_SERVER['REMOTE_ADDR'];
  794.         $docRoot $_SERVER['DOCUMENT_ROOT'];
  795.         if (strrpos($docRoot'https://tile.expert') || in_array($remoteAddr$whitelist)) {
  796.             $newImg explode('/'$imagePath);
  797.             $newImg urldecode($newImg[count($newImg) - 1]);
  798.             if (!is_dir($docRoot '/media/cache/slide-show/')) {
  799.                 mkdir($docRoot '/media/cache/slide-show/'0777);
  800.             }
  801.             if (!file_exists($docRoot '/media/cache/slide-show/' $newImg)) {
  802.                 if (in_array($remoteAddr$whitelist)) {
  803.                     $imgSrc $docRoot '/media/cache/slide-show/new-' $newImg;
  804.                     copy($imagePath$imgSrc);
  805.                 } else {
  806.                     $imgSrc $imagePath;
  807.                 }
  808.                 $image = new Imagick($imgSrc);
  809.                 $image->thumbnailImage(110110);
  810.                 $image->writeImage($docRoot '/media/cache/slide-show/' $newImg);
  811.             }
  812.             return '/media/cache/slide-show/' $newImg;
  813.         } else {
  814.             return $imagePath;
  815.         }
  816.         /*} catch(Exception $e) {
  817.             echo 'Exception: ', $e->getMessage(), "n";
  818.         }*/
  819.     }
  820.     /**
  821.      * @param $str
  822.      * @param $data
  823.      * @param null $number
  824.      * @param int $sex
  825.      * @param null $bankTransfer
  826.      *
  827.      * @return mixed
  828.      *
  829.      * @throws Exception
  830.      */
  831.     public function setDataHistoryOrder($str$data$number null$sex 1$bankTransfer null)
  832.     {
  833.         $mask = [
  834.             '%table%' => '',
  835.             '%table2%' => '',
  836.             '%tableForReview%' => '',
  837.             '%managerName%' => '',
  838.             '%managerEmail%' => '',
  839.             '%managerPhone%' => '',
  840.             '%invoiceAttachmentText%' => '',
  841.         ];
  842.         if (!empty($number)) {
  843.             $mask['%number%'] = '<a href="#">' $number '</a>';
  844.         }
  845.         unset($data['country']);
  846.         if (isset($data['%lift%'])) {
  847.             $data['%lift%'] = App::trans($data['%lift%'], App::getCurLocale());
  848.         }
  849.         $data['%link%'] = '#';
  850.         $data['%acceptLink%'] = '#confirmTheDateBlock';
  851.         $data['%setDateLink%'] = '#confirmTheDateBlock';
  852.         $data['%cancelLink%'] = '#confirmTheDateBlock';
  853.         $data['%designLinkLeft%'] = '';
  854.         $data['%designLinkRight%'] = '';
  855.         $data['%designFooterStart%'] = '';
  856.         $data['%designFooterEnd%'] = '';
  857.         $data['%bankTransfer%'] = $bankTransfer App::trans('var_bank_transfer') : '';
  858.         if (!empty($data['%sysPayment%'])) {
  859.             $data['%sysPayment%'] = App::trans($data['%sysPayment%'], App::getCurLocale());
  860.         }
  861.         if (!empty($data['%sysPayment2%'])) {
  862.             $data['%sysPayment2%'] = App::trans($data['%sysPayment2%'], App::getCurLocale());
  863.         }
  864.         if (empty($data['%offsetDate2%'])) {
  865.             $data['%offsetDate2%'] = App::trans('buyOrder.offsetData_2'App::getCurLocale());
  866.             $data['%OffsetDate2%'] = StrHelper::ucFirstOnly($data['%offsetDate2%']);
  867.         }
  868.         $data['%fio%'] = $data['%fio%'] ?? '';
  869.         $t App::trans((== $sex 'title.man' 'title.woman'), App::getCurLocale());
  870.         if ('fr' != App::getCurLocale()) {
  871.             $data['%fio%'] = $t ' ' $data['%fio%'];
  872.         } else {
  873.             $data['%fio%'] = $t;
  874.         }
  875.         $data['%fio%'] .= App::getCurLocale() ? '!' ',';
  876.         $data array_merge($mask$data);
  877.         $dataKey array_keys($data);
  878.         $data array_values($data);
  879.         // получаем необходимое письма и подставляем переменные
  880.         return str_replace($dataKey$data$str);
  881.     }
  882.     /**
  883.      * @param DateTime $date
  884.      *
  885.      * @return mixed
  886.      *
  887.      * @throws Exception
  888.      */
  889.     public function convertToHours($date)
  890.     {
  891.         $d = new DateTime();
  892.         return $d->diff($date)->format('%d') * 24;
  893.     }
  894.     /**
  895.      * @param Article $article
  896.      * @param array $param
  897.      *
  898.      * @return string
  899.      *
  900.      * @throws Exception
  901.      */
  902.     public function price($article$param = [])
  903.     {
  904.         return LocaleHelper::getPrice($article$param);
  905.     }
  906.     /**
  907.      * @param ArticlePriceDiscount $priceDiscount
  908.      * @param array $param
  909.      *
  910.      * @return array
  911.      *
  912.      * @throws Exception
  913.      */
  914.     public function priceDiscount($priceDiscount$param = [])
  915.     {
  916.         return LocaleHelper::getPriceDiscount($priceDiscount$param);
  917.     }
  918.     /**
  919.      * @param Article $article
  920.      * @param array $param
  921.      *
  922.      * @return string
  923.      *
  924.      * @throws Exception
  925.      */
  926.     public function priceMq($article$param = [])
  927.     {
  928.         return LocaleHelper::getPriceMq($article$param);
  929.     }
  930.     /**
  931.      * @param Article $article
  932.      * @param array $param
  933.      * @param int $type
  934.      *
  935.      * @return string
  936.      *
  937.      * @throws Exception
  938.      */
  939.     public function measure($article$param = [], $type 1)
  940.     {
  941.         return LocaleHelper::getMeasure($article$param$type);
  942.     }
  943.     /**
  944.      * @param $val
  945.      * @param int $type
  946.      *
  947.      * @return float
  948.      */
  949.     public function convertFt($val$type 1): float
  950.     {
  951.         return ConversionHelper::convertFt((float) $val$type);
  952.     }
  953.     /**
  954.      * @param $val
  955.      * @param int $type
  956.      *
  957.      * @return float
  958.      */
  959.     public function convertSqFt($val$type 1): float
  960.     {
  961.         return ConversionHelper::convertSqFt((float) $val$type);
  962.     }
  963.     /**
  964.      * @param $val
  965.      * @param int $type
  966.      *
  967.      * @return float
  968.      */
  969.     public function convertKgLb($val$type 1): float
  970.     {
  971.         return ConversionHelper::convertKgLb((float) $val$type);
  972.     }
  973.     /**
  974.      * @param float $val - цена в EUR
  975.      * @param string|null $currency - валюта в которую переводим
  976.      * @return float
  977.      * @throws Exception
  978.      */
  979.     public function convertPrice(float $valstring $currency null): float
  980.     {
  981.         if (!$currency) {
  982.             $currency LocaleHelper::getCur();
  983.         }
  984.         return CurrencyRateHelper::convertPrice($currency$val);
  985.     }
  986.     /**
  987.      * @param $str
  988.      * @return string
  989.      * @throws Exception
  990.      */
  991.     public function currency($str null)
  992.     {
  993.         return LocaleHelper::getCurrency($str);
  994.     }
  995.     /**
  996.      * @param BuyOrder $order
  997.      * @return array
  998.      * @throws Exception
  999.      */
  1000.     public function orderSum(BuyOrder $order)
  1001.     {
  1002.         return OrderHelper::sum($order);
  1003.     }
  1004.     /**
  1005.      * @param BuyOrderArticle $item
  1006.      * @param BuyOrder $order
  1007.      * @return bool
  1008.      */
  1009.     public function availabilityItemOrder(BuyOrderArticle $itemBuyOrder $order)
  1010.     {
  1011.         $specPrice $order->getSpecPrice();
  1012.         $orderStatusId $order->getStatus();
  1013.         return OrderHelper::availabilityItemOrder($item$specPrice$orderStatusId);
  1014.     }
  1015.     /**
  1016.      * @param BuyOrder $order
  1017.      * @return float
  1018.      * @throws Exception
  1019.      */
  1020.     public function deliveryWVat(BuyOrder $order)
  1021.     {
  1022.         return OrderHelper::deliveryWVat($order);
  1023.     }
  1024.     /**
  1025.      * @param BuyOrder $order
  1026.      * @return bool
  1027.      * @throws Exception
  1028.      */
  1029.     public function asVat(BuyOrder $order)
  1030.     {
  1031.         return OrderHelper::asVat($order);
  1032.     }
  1033.     /**
  1034.      * @param BuyOrder $order
  1035.      * @return bool
  1036.      * @throws Exception
  1037.      */
  1038.     public function homeCountryVat(BuyOrder $order)
  1039.     {
  1040.         return OrderHelper::homeCountryVat($order);
  1041.     }
  1042.     /**
  1043.      * @param Article $article
  1044.      * @param array $param
  1045.      * @param int $type
  1046.      *
  1047.      * @return string
  1048.      *
  1049.      * @throws Exception
  1050.      */
  1051.     public function packagingCount($article$param = [], $type 1)
  1052.     {
  1053.         return LocaleHelper::getPackagingCount($article$param$type);
  1054.     }
  1055.     /**
  1056.      * @param Article $article
  1057.      * @param array $param
  1058.      *
  1059.      * @return string
  1060.      *
  1061.      * @throws Exception
  1062.      */
  1063.     public function pallet($article$param = [])
  1064.     {
  1065.         return LocaleHelper::getPallet($article$param);
  1066.     }
  1067.     /**
  1068.      * @param Article $article
  1069.      * @param float|null $amount
  1070.      * @param array $param
  1071.      * @param int $type
  1072.      *
  1073.      * @return string
  1074.      *
  1075.      * @throws Exception
  1076.      */
  1077.     public function amount($article$amount null$param = [], $type 1)
  1078.     {
  1079.         return LocaleHelper::getAmount($article$amount$param$type);
  1080.     }
  1081.     /**
  1082.      * @param Article $article
  1083.      * @param array $param
  1084.      *
  1085.      * @return string
  1086.      *
  1087.      * @throws Exception
  1088.      */
  1089.     public function weight($article$param = [])
  1090.     {
  1091.         return LocaleHelper::getWeight($article$param);
  1092.     }
  1093.     /**
  1094.      * @param float|null $weight
  1095.      * @param bool $with
  1096.      * @param BuyOrder|null $order
  1097.      *
  1098.      * @return string
  1099.      *
  1100.      * @throws Exception
  1101.      */
  1102.     public function weightLabel(?float $weight 1.0bool $with true, ?string $measure null): string
  1103.     {
  1104.         return LocaleHelper::weightLabel($weight$with$measure);
  1105.     }
  1106.     /**
  1107.      * @param array $param
  1108.      *
  1109.      * @return bool
  1110.      *
  1111.      * @throws Exception
  1112.      */
  1113.     public function measureGb($param = [])
  1114.     {
  1115.         return LocaleHelper::measureGb($param);
  1116.     }
  1117.     /**
  1118.      * @param $orderItem
  1119.      *
  1120.      * @return string
  1121.      *
  1122.      * @throws Exception
  1123.      */
  1124.     public function orderItemTime(BuyOrderArticle $orderItem): string
  1125.     {
  1126.         return OrderItemHelper::getItemTime($orderItem);
  1127.     }
  1128.     /**
  1129.      * @param int $type
  1130.      * @param null $country
  1131.      *
  1132.      * @return string
  1133.      *
  1134.      * @throws Exception
  1135.      */
  1136.     public function dateMask($type 1$country null)
  1137.     {
  1138.         return LocaleHelper::dateMask($type$country);
  1139.     }
  1140.     /**
  1141.      * @return mixed|string|null
  1142.      *
  1143.      * @throws Exception
  1144.      */
  1145.     public function userCurrency()
  1146.     {
  1147.         return LocaleHelper::getCur();
  1148.     }
  1149.     /**
  1150.      * @throws Exception
  1151.      */
  1152.     public function userGA()
  1153.     {
  1154.         return CookieHelper::get('_ga');
  1155.     }
  1156.     /**
  1157.      * @return string
  1158.      *
  1159.      * @throws Exception
  1160.      */
  1161.     public function userCountry()
  1162.     {
  1163.         return App::getCurCountry();
  1164.     }
  1165.     /**
  1166.      * @return string|null
  1167.      *
  1168.      * @throws Exception
  1169.      */
  1170.     public function userMeasure()
  1171.     {
  1172.         return LocaleHelper::getUserMeasure();
  1173.     }
  1174.     /**
  1175.      * @param array $params
  1176.      *
  1177.      * @return bool
  1178.      *
  1179.      * @throws Exception
  1180.      */
  1181.     public function curLimit($params = [])
  1182.     {
  1183.         return LocaleHelper::getCurLimit($params);
  1184.     }
  1185.     /**
  1186.      * @return string
  1187.      *
  1188.      * @throws Exception
  1189.      */
  1190.     public function curLimitEx()
  1191.     {
  1192.         return LocaleHelper::getCurLimitEx();
  1193.     }
  1194.     /**
  1195.      * Конвертация в дюймы
  1196.      *
  1197.      * @param float $val
  1198.      * @param int $type 1 - мм, 0 - inch
  1199.      *
  1200.      * @return float
  1201.      */
  1202.     public function convertInch($val$type 1): float
  1203.     {
  1204.         return ConversionHelper::convertInch((float) $val$type);
  1205.     }
  1206.     /**
  1207.      * Возвращает минимальное ограничение по заказу
  1208.      *
  1209.      * @param array $param
  1210.      *
  1211.      * @return int
  1212.      *
  1213.      * @throws Exception
  1214.      */
  1215.     public function curLimitVal($param = [])
  1216.     {
  1217.         return LocaleHelper::getCurLimitVal($param);
  1218.     }
  1219.     /**
  1220.      * Определяет летнее/зимнее время по Лондону
  1221.      *
  1222.      * @return bool
  1223.      */
  1224.     public function typeTime()
  1225.     {
  1226.         $old date_default_timezone_get();
  1227.         date_default_timezone_set('Europe/London');
  1228.         $ts time();
  1229.         $dy date('I'$ts);
  1230.         date_default_timezone_set($old);
  1231.         if (== $dy) {
  1232.             return (string) '1';
  1233.         } else {
  1234.             return (string) '0';
  1235.         }
  1236.     }
  1237.     /**
  1238.      * @param $string
  1239.      *
  1240.      * @return mixed
  1241.      */
  1242.     public function replaceSymbolsTitleFilter($string)
  1243.     {
  1244.         return TranslitHelper::replaceSymbolsTitleFilter($string);
  1245.     }
  1246.     /**
  1247.      * @param string $price
  1248.      *
  1249.      * @return mixed
  1250.      */
  1251.     public function wrapCents($price)
  1252.     {
  1253.         $price = (string) $price;
  1254.         $sign '.';
  1255.         if (!strpos($price$sign)) {
  1256.             $sign ',';
  1257.         }
  1258.         if (== count(explode($sign$price))) {
  1259.             return str_replace($sign$sign '<span class="top-aligned-cents">'$price) . '</span>';
  1260.         } else {
  1261.             return $price;
  1262.         }
  1263.     }
  1264.     /**
  1265.      * @param $coll
  1266.      * @param array $param
  1267.      *
  1268.      * @return mixed
  1269.      *
  1270.      * @throws Exception
  1271.      */
  1272.     public function prMin($coll$param = [])
  1273.     {
  1274.         return LocaleHelper::getPrMin($coll$param);
  1275.     }
  1276.     /**
  1277.      * @param string $type ['collection'|'article'|'factory'|'publication']
  1278.      * @param array|object $data
  1279.      *
  1280.      * @return mixed
  1281.      */
  1282.     public function pathGenerate($type$data)
  1283.     {
  1284.         return PathHelper::pathGenerate($type$data);
  1285.     }
  1286.     /**
  1287.      * получить координаты бирки
  1288.      *
  1289.      * @param $article
  1290.      * @param $interior
  1291.      *
  1292.      * @return mixed
  1293.      *
  1294.      * @throws DBALException
  1295.      */
  1296.     public function getCoords($article$interior)
  1297.     {
  1298.         return SliderHelper::getCoords($article$interior);
  1299.     }
  1300.     /**
  1301.      * возвращает является ли артикул заглавным в интерьере
  1302.      *
  1303.      * @param $article
  1304.      * @param $interior
  1305.      *
  1306.      * @return mixed
  1307.      *
  1308.      * @throws DBALException
  1309.      */
  1310.     public function getInteriorHead($article$interior)
  1311.     {
  1312.         return SliderHelper::getInteriorHead($article$interior);
  1313.     }
  1314.     public function timestamp()
  1315.     {
  1316.         return strtotime('now') + 5000;
  1317.     }
  1318.     /**
  1319.      * @param bool $full !deprecated
  1320.      *
  1321.      * @return string
  1322.      */
  1323.     public function getCurLocale($full false)
  1324.     {
  1325.         return App::getCurLocale($full);
  1326.     }
  1327.     /**
  1328.      * @param bool $full
  1329.      *
  1330.      * @return string
  1331.      */
  1332.     public function userLocale($full false)
  1333.     {
  1334.         return App::getCurLocale($full);
  1335.     }
  1336.     /**
  1337.      * Меняет точку на запятую в дробных значениях для стран где принят такой формат
  1338.      *
  1339.      * @param float $val
  1340.      * @param int $decimals
  1341.      * @param bool $float если true то вернёт цифровое значение
  1342.      *
  1343.      * @return mixed
  1344.      */
  1345.     public function floatSing($val$decimals 2$float false)
  1346.     {
  1347.         return LocaleHelper::floatSign($val$decimals$float);
  1348.     }
  1349.     public function bcdiv($val$decimals 2)
  1350.     {
  1351.         return bcdiv($val1$decimals);
  1352.     }
  1353.     /**
  1354.      * Меняет точку на запятую в дробных значениях для стран где принят такой формат;
  1355.      * для 3 знаков после запятой
  1356.      *
  1357.      * @param float $val
  1358.      * @param int $decimals
  1359.      * @param bool $float если true то вернёт цифровое значение
  1360.      *
  1361.      * @return mixed
  1362.      */
  1363.     public function floatSingDec($val$decimals 3$float false)
  1364.     {
  1365.         return LocaleHelper::floatSign($val$decimals$float);
  1366.     }
  1367.     /**
  1368.      * Удаляет дробную часть числа
  1369.      *
  1370.      * @param float $val
  1371.      *
  1372.      * @return int
  1373.      */
  1374.     public function removeDec($val)
  1375.     {
  1376.         return round($val0);
  1377.     }
  1378.     /**
  1379.      * вывод атрибутов в шаблоне
  1380.      *
  1381.      * @param array $attributes
  1382.      *
  1383.      * @return int
  1384.      */
  1385.     public function showAttributes($attributes)
  1386.     {
  1387.         $name = [];
  1388.         $locale App::getCurLocale();
  1389.         foreach ($attributes as $key => $attribute) {
  1390.             $a is_object($attribute) ? $attribute->getAlias() : $attribute['alias'];
  1391.             $alias $this->translator->trans($a);
  1392.             if ($key 0) {
  1393.                 if ('de' == $locale) {
  1394.                     $alias TranslitHelper::replaceAttributesTitle($alias);
  1395.                 } elseif ('left_menu_3d' == $a) {
  1396.                     $alias mb_strtoupper(TranslitHelper::replaceAttributesTitle($alias));
  1397.                 } else {
  1398.                     $alias mb_strtolower(TranslitHelper::replaceAttributesTitle($alias));
  1399.                 }
  1400.             }
  1401.             $name[] = trim($alias);
  1402.         }
  1403.         return implode(', '$name);
  1404.     }
  1405.     /**
  1406.      * вывод атрибутов style в шаблоне
  1407.      *
  1408.      * @param $attributes
  1409.      *
  1410.      * @return mixed
  1411.      */
  1412.     public function showStyleAttributes($attributes)
  1413.     {
  1414.         $name = [];
  1415.         $locale App::getCurLocale();
  1416.         /* @var ListStyle $style */
  1417.         if ('en' == $locale) {
  1418.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1419.             foreach ($attributes as $key => $style) {
  1420.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1421.                 $alias $this->translator->trans($a);
  1422.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1423.                 $name[] = trim($alias);
  1424.             }
  1425.             if ($count 1) {
  1426.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1427.             } else {
  1428.                 $output ucfirst(implode(', '$name));
  1429.             }
  1430.         } elseif ('it' == $locale) {
  1431.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1432.             foreach ($attributes as $key => $style) {
  1433.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1434.                 $alias $this->translator->trans($a);
  1435.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1436.                 $name[] = trim($alias);
  1437.             }
  1438.             if ($count 1) {
  1439.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1440.             } else {
  1441.                 $output ucfirst(implode(', '$name));
  1442.             }
  1443.         } elseif ('es' == $locale) {
  1444.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1445.             foreach ($attributes as $key => $style) {
  1446.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1447.                 $alias $this->translator->trans($a);
  1448.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1449.                 $name[] = trim($alias);
  1450.             }
  1451.             if ($count 1) {
  1452.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1453.             } else {
  1454.                 $output ucfirst(implode(', '$name));
  1455.             }
  1456.         } elseif ('fr' == $locale) {
  1457.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1458.             foreach ($attributes as $key => $style) {
  1459.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1460.                 $alias $this->translator->trans($a);
  1461.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1462.                 $name[] = trim($alias);
  1463.             }
  1464.             if ($count 1) {
  1465.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1466.             } else {
  1467.                 $output ucfirst(implode(', '$name));
  1468.             }
  1469.         } elseif ('de' == $locale) {
  1470.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1471.             foreach ($attributes as $key => $style) {
  1472.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1473.                 $alias $this->translator->trans($a);
  1474.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1475.                 $name[] = trim($alias);
  1476.             }
  1477.             if ($count 1) {
  1478.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1479.             } else {
  1480.                 $output ucfirst(implode(', '$name));
  1481.             }
  1482.             $output ucfirst(implode(', '$name));
  1483.         } elseif ('pl' == $locale) {
  1484.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1485.             foreach ($attributes as $key => $style) {
  1486.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1487.                 $alias $this->translator->trans($a);
  1488.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1489.                 $name[] = trim($alias);
  1490.             }
  1491.             if ($count 1) {
  1492.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1493.             } else {
  1494.                 $output ucfirst(implode(', '$name));
  1495.             }
  1496.         } elseif ('nl' == $locale) {
  1497.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1498.             foreach ($attributes as $key => $style) {
  1499.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1500.                 $alias $this->translator->trans($a);
  1501.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1502.                 $name[] = trim($alias);
  1503.             }
  1504.             if ($count 1) {
  1505.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1506.             } else {
  1507.                 $output ucfirst(implode(', '$name));
  1508.             }
  1509.         } elseif ('fi' == $locale) {
  1510.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1511.             foreach ($attributes as $key => $style) {
  1512.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1513.                 $alias $this->translator->trans($a);
  1514.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1515.                 $name[] = trim($alias);
  1516.             }
  1517.             if ($count 1) {
  1518.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1519.             } else {
  1520.                 $output ucfirst(implode(', '$name));
  1521.             }
  1522.         } else {
  1523.             $count is_object($attributes) ? count($attributes->count()) : count($attributes);
  1524.             foreach ($attributes as $key => $style) {
  1525.                 $a is_object($style) ? $style->getAlias() : $style['alias'];
  1526.                 $alias $this->translator->trans($a);
  1527.                 $alias $count mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
  1528.                 $name[] = trim($alias);
  1529.             }
  1530.             if ($count 1) {
  1531.                 $output ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' implode(', '$name));
  1532.             } else {
  1533.                 $output ucfirst(implode(', '$name));
  1534.             }
  1535.         }
  1536.         return $output;
  1537.     }
  1538.     /**
  1539.      * @param $str
  1540.      *
  1541.      * @return string
  1542.      */
  1543.     public static function symbolCyrillicUnderline($str)
  1544.     {
  1545.         return TranslitNameHelper::returnStrCyrillicSymbolUnderline($str);
  1546.     }
  1547.     public function lenThanSomeSymbol($str)
  1548.     {
  1549.         return TranslitNameHelper::lenThanSomeSymbol($str);
  1550.     }
  1551.     /**
  1552.      * @param $date
  1553.      *
  1554.      * @return mixed|string
  1555.      */
  1556.     public static function humanData($date)
  1557.     {
  1558.         return HumanDataHelper::get((int) $date);
  1559.     }
  1560.     public function isEmployee(?string $email): bool
  1561.     {
  1562.         return UserHelper::isEmployee($email);
  1563.     }
  1564.     /**
  1565.      * @param ?int $type
  1566.      * @param ?string $locale
  1567.      *
  1568.      * @return array
  1569.      *
  1570.      * @throws Exception
  1571.      */
  1572.     public static function humanSampleType(?int $type 1, ?string $locale null): array
  1573.     {
  1574.         return OrderItemHelper::humanSampleType($type$locale);
  1575.     }
  1576.     /**
  1577.      * @param BuyOrderArticle|array $article
  1578.      * @param array $params
  1579.      * @param bool $inch
  1580.      * @param null $locale
  1581.      *
  1582.      * @return string
  1583.      *
  1584.      * @throws Exception
  1585.      */
  1586.     public static function sampleFormat($article$params$inch false$locale null)
  1587.     {
  1588.         return OrderItemHelper::sampleFormat($article$params$inch$locale);
  1589.     }
  1590.     /**
  1591.      * @param $order
  1592.      * @param bool $withLimit
  1593.      * @return bool
  1594.      * @throws Exception
  1595.      */
  1596.     public static function readyCreate($order$withLimit true)
  1597.     {
  1598.         return OrderHelper::readyCreate($order$withLimit);
  1599.     }
  1600.     /**
  1601.      * @param $order
  1602.      * @param bool $withLimit
  1603.      * @return bool
  1604.      * @throws Exception
  1605.      */
  1606.     public static function checkForSend($order$withLimit true)
  1607.     {
  1608.         return OrderHelper::checkForSend($order$withLimit);
  1609.     }
  1610.     /**
  1611.      * @return bool
  1612.      *
  1613.      * @throws Exception
  1614.      */
  1615.     public static function isWithoutVATPrice()
  1616.     {
  1617.         return false !== LocaleHelper::isWithoutVATPrice(10);
  1618.     }
  1619.     /**
  1620.      * @throws Exception
  1621.      */
  1622.     public static function includeVATAlways(): float
  1623.     {
  1624.         return (float) LocaleHelper::includeVATAlways();
  1625.     }
  1626.     /**
  1627.      * @return array
  1628.      */
  1629.     public static function baseProps()
  1630.     {
  1631.         return [
  1632.             'baseUrl' => /*App::getRequest()->getSchemeAndHttpHost() . */ App::getRequest()->getBaseUrl(),
  1633.             'locale' => App::getCurLocale(true),
  1634.             'lang' => App::getCurLocale(),
  1635.         ];
  1636.     }
  1637.     public static function vatRequiredState(BuyOrder $order): bool
  1638.     {
  1639.         if ($order->getDeliveryCountry()) {
  1640.             $country strtolower($order->getDeliveryCountry()->getCode());
  1641.         } else {
  1642.             $country 'at';
  1643.         }
  1644.         return in_array($countryOrderHelper::vatRequired()['char']);
  1645.     }
  1646.     /**
  1647.      * @param BuyOrder $order
  1648.      * @return int
  1649.      * @throws Exception
  1650.      */
  1651.     public static function orderPercent(BuyOrder $order)
  1652.     {
  1653.         return OrderHelper::vatPercent($order);
  1654.     }
  1655.     /**
  1656.      * @param BuyOrder $order
  1657.      * @return string
  1658.      * @throws Exception
  1659.      */
  1660.     public static function orderVatText(BuyOrder $order)
  1661.     {
  1662.         return OrderHelper::vatText($order);
  1663.     }
  1664.     public static function orderMsg(BuyOrder $order)
  1665.     {
  1666.         return OrderHelper::msg($order);
  1667.     }
  1668.     /**
  1669.      * @param int $orderId
  1670.      * @return string
  1671.      */
  1672.     public static function orderStatusAliasByStatusId(int $orderId): string
  1673.     {
  1674.         return BuyOrderStatusEnum::from($orderId)->getAlias();
  1675.     }
  1676.     /**
  1677.      * @param BuyOrder $order
  1678.      * @param int|bool $flag
  1679.      * @return float|int
  1680.      * @throws Exception
  1681.      */
  1682.     public static function paymentPercent(BuyOrder $order$flag false)
  1683.     {
  1684.         return OrderHelper::paymentPercent($order$flag);
  1685.     }
  1686.     /**
  1687.      * @param $val
  1688.      * @param $percent
  1689.      * @param bool $type
  1690.      * @return float
  1691.      */
  1692.     public function getPercent($val$percent$type true)
  1693.     {
  1694.         return OrderHelper::percent($val$percent$type);
  1695.     }
  1696.     /**
  1697.      * @param BuyOrder $order
  1698.      * @return array
  1699.      * @throws Exception
  1700.      */
  1701.     public function orderParams(BuyOrder $order)
  1702.     {
  1703.         return OrderHelper::params($order);
  1704.     }
  1705.     /**
  1706.      * @param BuyOrder $order
  1707.      * @return float|int
  1708.      * @throws Exception
  1709.      */
  1710.     public function vatFactor(BuyOrder $order)
  1711.     {
  1712.         return OrderHelper::vatFactor(OrderHelper::vatPercent($order));
  1713.     }
  1714.     /**
  1715.      * @param BuyOrder $order
  1716.      * @return bool
  1717.      */
  1718.     public function isHoliday(BuyOrder $order)
  1719.     {
  1720.         return OrderHelper::isHoliday($order);
  1721.     }
  1722.     /**
  1723.      * @param BuyOrder $order
  1724.      * @param bool $euro
  1725.      * @return float
  1726.      */
  1727.     public function totalSum(BuyOrder $order$euro false)
  1728.     {
  1729.         return OrderHelper::totalSum($order$euro);
  1730.     }
  1731.     /**
  1732.      * @param BuyOrder $order
  1733.      * @return bool
  1734.      * @throws Exception
  1735.      */
  1736.     public function statePaymentButton(BuyOrder $order)
  1737.     {
  1738.         return OrderHelper::statePaymentButton($order);
  1739.     }
  1740.     /**
  1741.      * @param BuyOrder $order
  1742.      * @return bool
  1743.      * @throws Exception
  1744.      */
  1745.     public function onlySamples(BuyOrder $order)
  1746.     {
  1747.         return OrderHelper::onlySamples($order);
  1748.     }
  1749.     /**
  1750.      * @param BuyOrder $order
  1751.      * @return bool
  1752.      */
  1753.     public function noVat(BuyOrder $order): bool
  1754.     {
  1755.         return OrderHelper::noVat($order);
  1756.     }
  1757.     public function cmToInch($val): float
  1758.     {
  1759.         if (is_numeric($val)) {
  1760.             return ConversionHelper::convertInch((float) $valConversionHelper::CM);
  1761.         }
  1762.         return 0;
  1763.     }
  1764.     public function resolverScriptSize($item): string
  1765.     {
  1766.         if (is_array($item)) {
  1767.             if (!empty($item['shape']) && $item['shape'] == 7) {
  1768.                 return 'L';
  1769.             } else {
  1770.                 return '&#8960;';
  1771.             }
  1772.         } elseif ($item->getShape() && $item->getShape()->getId() == 7) {
  1773.             return 'L';
  1774.         } else {
  1775.             return '&#8960;';
  1776.         }
  1777.     }
  1778.     public function getUnreadCount(): int
  1779.     {
  1780.         $token UserHelper::getInstance()->getToken();
  1781.         $chat $this->chatBRepository->findOneBy(['token' => $token]);
  1782.         if ($chat) {
  1783.             return $this->chatBMessageRepository->getUnreadMessagesCountForChat($chat);
  1784.         }
  1785.         return 0;
  1786.     }
  1787.     public function getJwt(): string
  1788.     {
  1789.         $token UserHelper::getInstance()->getToken();
  1790.         return $this->jwtGenerator->generateJWT($token);
  1791.     }
  1792.     public function getUserChannel(): string
  1793.     {
  1794.         $token UserHelper::getInstance()->getToken();
  1795.         return "general#$token";
  1796.     }
  1797.     public function useRTWidget(): bool
  1798.     {
  1799.         $setting $this->boolDBSettingRepository->findOneByName('RTWidget');
  1800.         if (null === $setting) {
  1801.             return false;
  1802.         }
  1803.         return $setting->getVal();
  1804.     }
  1805.     /**
  1806.      * @throws Exception
  1807.      */
  1808.     public function getWidgetId(): string
  1809.     {
  1810.         $lang App::getCurLocale(false);
  1811.         $widget $this->widgetRepository->findOneBy(['lang' => $lang]);
  1812.         if (!$widget) {
  1813.             throw new Exception(sprintf('Для языка "%s" не заведен виджет в базе данных'$lang));
  1814.         }
  1815.         return $widget->getWidgetId();
  1816.     }
  1817.     /**
  1818.      * Для испанских клиентов делаем возможность платить Visa, MasterCard, Maestro через Адиен
  1819.      * Все остальные - через БрайнТри
  1820.      */
  1821.     public function getUrlForPaymentByVisa(BuyOrder $order): string
  1822.     {
  1823.         if (OrderHelper::country($order) === CountryNumberEnum::ES) {
  1824.             return $this->urlGenerator->generate('app_credit_card_form_old', ['hash' => $order->getHash()]);
  1825.         }
  1826.         return $this->urlGenerator->generate('app_credit_card_form', ['hash' => $order->getHash()]);
  1827.     }
  1828.     /**
  1829.      * Для испанских клиентов делаем возможность платить Amex через Адиен
  1830.      * Для валют, кроме евро, долларов и фунтов платить Amex через Адиен
  1831.      * Все остальные - платить Amex через БрайнТри
  1832.      */
  1833.     public function getUrlForPaymentByAmex(BuyOrder $order): string
  1834.     {
  1835.         if (OrderHelper::country($order) === CountryNumberEnum::ES) {
  1836.             return $this->urlGenerator->generate('app_credit_card_form_old', ['hash' => $order->getHash()]);
  1837.         }
  1838.         if (OrderHelper::availableAdyenAmex($order)) {
  1839.             return $this->urlGenerator->generate('app_credit_card_form_old', ['hash' => $order->getHash()]);
  1840.         }
  1841.         return $this->urlGenerator->generate('app_credit_card_form', ['hash' => $order->getHash()]);
  1842.     }
  1843.     /**
  1844.      * Форматирует цену с символом валюты с учетом страны
  1845.      * Для US, UK, Canada - символ перед суммой ($ 100)
  1846.      * Для остальных стран - символ после суммы (100 €)
  1847.      *
  1848.      * @param string|float $amount Сумма (уже отформатированная или число)
  1849.      * @param string $currencySymbol Символ валюты
  1850.      * @param int|string|null $countryId ID страны
  1851.      * @return string
  1852.      */
  1853.     public function formatPriceWithCurrency($amountstring $currencySymbol$countryId null): string
  1854.     {
  1855.         if ($countryId !== null && CountryNumberEnum::usesPrefixCurrencyNotation((int) $countryId)) {
  1856.             return $currencySymbol ' ' $amount;
  1857.         }
  1858.         return $amount ' ' $currencySymbol;
  1859.     }
  1860. }