<?php
namespace WebBundle\Twig;
use DateTime;
use Doctrine\DBAL\DBALException;
use Exception;
use FlexApp\Constant\TimeConstant;
use FlexApp\Repository\BoolDBSettingRepository;
use FlexApp\Repository\ChatBMessageRepository;
use FlexApp\Repository\ChatBRepository;
use FlexApp\Repository\WidgetRepository;
use FlexApp\Service\CalendarService;
use FlexApp\Service\JWTGenerator;
use Imagick;
use ImagickException;
use Import1CBundle\Helper\v3\BiConst;
use Import1CBundle\Helper\v3\TranslitNameHelper;
use Memcache;
use ReflectionClass;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Twig\Extension\AbstractExtension;
use Twig\Extension\GlobalsInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;
use WebBundle\Entity\Article;
use WebBundle\Entity\ArticlePriceDiscount;
use WebBundle\Entity\BuyOrder;
use WebBundle\Entity\BuyOrderArticle;
use WebBundle\Entity\Factory;
use WebBundle\Entity\ListStyle;
use WebBundle\Enum\BuyOrderStatusEnum;
use WebBundle\Enum\CountryNumberEnum;
use WebBundle\Helper\App;
use WebBundle\Helper\CalendarHelper;
use WebBundle\Helper\ConversionHelper;
use WebBundle\Helper\CookieHelper;
use WebBundle\Helper\HumanDataHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\OrderHelper;
use WebBundle\Helper\OrderItemHelper;
use WebBundle\Helper\PathHelper;
use WebBundle\Helper\SliderHelper;
use WebBundle\Helper\StrHelper;
use WebBundle\Helper\TranslitHelper;
use WebBundle\Helper\TwigTe;
use WebBundle\Helper\UserHelper;
class AppExtension extends AbstractExtension implements GlobalsInterface
{
/** @required */
public ChatBRepository $chatBRepository;
/** @required */
public ChatBMessageRepository $chatBMessageRepository;
/** @required */
public BoolDBSettingRepository $boolDBSettingRepository;
/** @required */
public WidgetRepository $widgetRepository;
/** @required */
public JWTGenerator $jwtGenerator;
private ContainerInterface $container;
private TranslatorInterface $translator;
private UrlGeneratorInterface $urlGenerator;
public function __construct(
ContainerInterface $container,
TranslatorInterface $translator,
UrlGeneratorInterface $urlGenerator
) {
$this->container = $container;
$this->translator = $translator;
$this->urlGenerator = $urlGenerator;
}
public function getName(): string
{
return 'app_extension';
}
/**
* Регистрируем глобальные переменные
* @throws Exception
*/
public function getGlobals(): array
{
return [
'fullDomain' => App::getParameter('full_domain'),
'userSession' => $_COOKIE,
'te' => TwigTe::that(),
'csrf_token' => App::getContainer()->get('security.csrf.token_manager')->getToken('authenticate')->getValue(),
'portalWsServer' => $this->container->getParameter('portal_ws_server'),
'token' => UserHelper::getInstance()->getToken(),
'centrifugoConnectionUrl' => $this->container->getParameter('centrifugo.connection_url'),
];
}
public function getClassName($entity): string
{
return (new ReflectionClass($entity))->getShortName();
}
public function getFunctions(): array
{
return [
'className' => new TwigFunction('className', [$this, 'getClassName']),
'measureGb' => new TwigFunction('measureGb', [$this, 'measureGb']),
'currency' => new TwigFunction('currency', [$this, 'currency']),
'userLocale' => new TwigFunction('userLocale', [$this, 'userLocale']),
'orderItemTime' => new TwigFunction('orderItemTime', [$this, 'orderItemTime']),
'dateMask' => new TwigFunction('dateMask', [$this, 'dateMask']),
'userCurrency' => new TwigFunction('userCurrency', [$this, 'userCurrency']),
'userGA' => new TwigFunction('userGA', [$this, 'userGA']),
'userCountry' => new TwigFunction('userCountry', [$this, 'userCountry']),
'userMeasure' => new TwigFunction('userMeasure', [$this, 'userMeasure']),
'prMin' => new TwigFunction('prMin', [$this, 'prMin']),
'price' => new TwigFunction('price', [$this, 'price']),
'priceDiscount' => new TwigFunction('priceDiscount', [$this, 'priceDiscount']),
'typeTime' => new TwigFunction('typeTime', [$this, 'typeTime']),
'pathGenerate' => new TwigFunction('pathGenerate', [$this, 'pathGenerate']),
'timestamp' => new TwigFunction('timestamp', [$this, 'timestamp']),
'getCurLocale' => new TwigFunction('getCurLocale', [$this, 'getCurLocale']),
'footerLinks' => new TwigFunction('footerLinks', [$this, 'footerLinks']),
'curLimit' => new TwigFunction('curLimit', [$this, 'curLimit']),
'curLimitEx' => new TwigFunction('curLimitEx', [$this, 'curLimitEx']),
'curLimitVal' => new TwigFunction('curLimitVal', [$this, 'curLimitVal']),
'getCoords' => new TwigFunction('getCoords', [$this, 'getCoords']),
'getInteriorHead' => new TwigFunction('getInteriorHead', [$this, 'getInteriorHead']),
'show_attributes' => new TwigFunction('show_attributes', [$this, 'showAttributes']),
'wrapCents' => new TwigFunction('wrapCents', [$this, 'wrapCents']),
'show_style_attributes' => new TwigFunction('show_style_attributes', [$this, 'showStyleAttributes']),
'setides' => new TwigFunction('setides', [$this, 'setIdes']),
'isLogged' => new TwigFunction('isLogged', [$this, 'isLogged']),
'humanData' => new TwigFunction('humanData', [$this, 'humanData']),
'isEmployee' => new TwigFunction('isEmployee', [$this, 'isEmployee']),
'humanSampleType' => new TwigFunction('humanSampleType', [$this, 'humanSampleType']),
'SampleFormat' => new TwigFunction('SampleFormat', [$this, 'SampleFormat']),
'isWithoutVATPrice' => new TwigFunction('isWithoutVATPrice', [$this, 'isWithoutVATPrice']),
'includeVATAlways' => new TwigFunction('includeVATAlways', [$this, 'includeVATAlways']),
'baseProps' => new TwigFunction('baseProps', [$this, 'baseProps']),
'VatRequiredState' => new TwigFunction('VatRequiredState', [$this, 'vatRequiredState']),
'OrderPercent' => new TwigFunction('OrderPercent', [$this, 'orderPercent']),
'getPercent' => new TwigFunction('getPercent', [$this, 'getPercent']),
'sampleFormat' => new TwigFunction('sampleFormat', [$this, 'sampleFormat']),
'readyCreate' => new TwigFunction('readyCreate', [$this, 'readyCreate']),
'checkForSend' => new TwigFunction('checkForSend', [$this, 'checkForSend']),
'orderSum' => new TwigFunction('orderSum', [$this, 'orderSum']),
'availabilityItemOrder' => new TwigFunction('availabilityItemOrder', [$this, 'availabilityItemOrder']),
'asVat' => new TwigFunction('asVat', [$this, 'asVat']),
'homeCountryVat' => new TwigFunction('homeCountryVat', [$this, 'homeCountryVat']),
'deliveryWVat' => new TwigFunction('deliveryWVat', [$this, 'deliveryWVat']),
'paymentPercent' => new TwigFunction('paymentPercent', [$this, 'paymentPercent']),
'orderParams' => new TwigFunction('orderParams', [$this, 'orderParams']),
'vatFactor' => new TwigFunction('vatFactor', [$this, 'vatFactor']),
'isHoliday' => new TwigFunction('isHoliday', [$this, 'isHoliday']),
'totalSum' => new TwigFunction('totalSum', [$this, 'totalSum']),
'statePaymentButton' => new TwigFunction('statePaymentButton', [$this, 'statePaymentButton']),
'onlySamples' => new TwigFunction('onlySamples', [$this, 'onlySamples']),
'noVat' => new TwigFunction('noVat', [$this, 'noVat']),
'cmToInch' => new TwigFunction('cmToInch', [$this, 'cmToInch']),
'resolverScriptSize' => new TwigFunction('resolverScriptSize', [$this, 'resolverScriptSize']),
'getUnreadCount' => new TwigFunction('getUnreadCount', [$this, 'getUnreadCount']),
'getJwt' => new TwigFunction('getJwt', [$this, 'getJwt']),
'getUserChannel' => new TwigFunction('getUserChannel', [$this, 'getUserChannel']),
'OrderVatText' => new TwigFunction('OrderVatText', [$this, 'orderVatText']),
'OrderMsg' => new TwigFunction('OrderMsg', [$this, 'orderMsg']),
'orderStatusAliasByStatusId' => new TwigFunction('orderStatusAliasByStatusId', [$this, 'orderStatusAliasByStatusId']),
'assetAdm' => new TwigFunction('assetAdm', function ($link) {
$asset = !App::isGeneral() ? time() : App::getParameter('assets.version.adm');
return "{$link}?{$asset}";
}),
'useRTWidget' => new TwigFunction('useRTWidget', [$this, 'useRTWidget']),
'getWidgetId' => new TwigFunction('getWidgetId', [$this, 'getWidgetId']),
'getUrlForPaymentByVisa' => new TwigFunction('getUrlForPaymentByVisa', [$this, 'getUrlForPaymentByVisa']),
'getUrlForPaymentByAmex' => new TwigFunction('getUrlForPaymentByAmex', [$this, 'getUrlForPaymentByAmex']),
];
}
public function getFilters(): array
{
return [
new TwigFilter('emphasis', [$this, 'emphasisFilter']),
new TwigFilter('q_change', [$this, 'qChangeFilter']),
new TwigFilter('url_clear', [$this, 'urlClearFilter']),
new TwigFilter('preg_replace', [$this, 'pReplaceFilter']),
new TwigFilter('data_last', [$this, 'dataLastFilter']),
new TwigFilter('slice_word', [$this, 'cutTextForWords']),
new TwigFilter('insertHolidays', [$this, 'insertHolidays']),
new TwigFilter('convert_text', [$this, 'convertText']),
new TwigFilter('friendly_date', [$this, 'friendlyDate']),
new TwigFilter('caseString', [$this, 'getCase']),
new TwigFilter('separator_word', [$this, 'separatorWord']),
new TwigFilter('u_first', [$this, 'uFirst']),
new TwigFilter('l_first', [$this, 'lFirst']),
new TwigFilter('u_print', [$this, 'uPrint']),
new TwigFilter('strspaceless', [$this, 'strSpaceless']),
new TwigFilter('InteriorSizeTiny', [$this, 'interiorSizeTiny']),
new TwigFilter('path_collection', [$this, 'pathCollection']),
new TwigFilter('actual_name', [$this, 'actualName']),
new TwigFilter('less_content', [$this, 'lessContent']),
new TwigFilter('convertDate', [$this, 'convertDate']),
new TwigFilter('transform', [$this, 'transform']),
new TwigFilter('replace_umlaut', [$this, 'replaceUmlautChar']),
new TwigFilter('decodeHtml', [$this, 'decodeHtml']),
new TwigFilter('strPos', [$this, 'strPos']),
new TwigFilter('getFractPartLength', [$this, 'getFractPartLength']),
new TwigFilter('short_fio', [$this, 'getShortFio']),
new TwigFilter('transLit', [$this, 'transLit']),
new TwigFilter('makeThumbnail', [$this, 'makeThumbnail']),
new TwigFilter('prime', [$this, 'prime']),
new TwigFilter('mb_strlen', [$this, 'mbStrlen']),
new TwigFilter('setDataHistoryOrder', [$this, 'setDataHistoryOrder']),
new TwigFilter('convertToHours', [$this, 'convertToHours']),
new TwigFilter('price', [$this, 'price']),
new TwigFilter('priceMq', [$this, 'priceMq']),
new TwigFilter('measure', [$this, 'measure']),
new TwigFilter('currency', [$this, 'currency']),
new TwigFilter('convertFt', [$this, 'convertFt']),
new TwigFilter('convertSqFt', [$this, 'convertSqFt']),
new TwigFilter('convertKgLb', [$this, 'convertKgLb']),
new TwigFilter('packagingCount', [$this, 'packagingCount']),
new TwigFilter('pallet', [$this, 'pallet']),
new TwigFilter('amount', [$this, 'amount']),
new TwigFilter('weight', [$this, 'weight']),
new TwigFilter('weightLabel', [$this, 'weightLabel']),
new TwigFilter('measureGb', [$this, 'measureGb']),
new TwigFilter('convertInch', [$this, 'convertInch']),
new TwigFilter('replace_symbols_title', [$this, 'replaceSymbolsTitleFilter']),
new TwigFilter('floatSing', [$this, 'floatSing']),
new TwigFilter('bcdiv', [$this, 'bcdiv']),
new TwigFilter('floatSingDec', [$this, 'floatSingDec']),
new TwigFilter('removeDec', [$this, 'removeDec']),
new TwigFilter('pad', [$this, 'pad']),
new TwigFilter('HSCCard', [$this, 'HSCCard']),
new TwigFilter('symbolCyrillicUnderline', [$this, 'symbolCyrillicUnderline']),
new TwigFilter('lenThanSomeSymbol', [$this, 'lenThanSomeSymbol']),
new TwigFilter('declension', [$this, 'declension']),
];
}
/**
* передаём перевод для "артикул" с нужным окончанием, в зависимости от кол-ва и языка
*
* @param $num
* @param $expressions
* @param $lang
*
* @return mixed|null
*/
public function declension($num, $expressions, $lang)
{
$result = null;
$count = null;
$count = $num % 100;
if (1 == $num) {
$result = $expressions['0'];
} elseif ('ru' != $lang && 'pl' != $lang) {
$result = $expressions['1'];
} elseif ($count >= 5 && $count <= 20) {
$result = $expressions['2'];
} else {
$count = $count % 10;
if (1 == $count && 'ru' == $lang) {
$result = $expressions['0'];
} elseif ($count >= 2 && $count <= 4) {
$result = $expressions['1'];
} else {
$result = $expressions['2'];
}
}
return $result;
}
/**
* @param $str
*
* @return mixed
*/
public function HSCCard($str)
{
return htmlspecialchars($str, ENT_COMPAT | ENT_HTML401, 'UTF-8');
}
/**
* записать в кеш список ид артикулов распродажи
*
* @param $ides
*
* @return string
*/
public function setIdes($ides)
{
$memkey = 'memkey-' . UserHelper::getInstance()->getToken();
$memcache = new Memcache();
$memcache->connect(App::getParameter('memcache_host'), App::getParameter('memcache_port'));
if ($ides) {
$memcache->add($memkey, $ides, false, (int) TimeConstant::HOUR);
} else {
$memcache->delete($memkey);
}
return $memkey;
}
/**
* @return bool
*
* @throws Exception
*/
public function isLogged()
{
return (bool) App::getCurUser();
}
public function pad($str, $padLength, $sign)
{
return str_pad($str, $padLength, $sign, STR_PAD_LEFT);
}
public function mbStrlen($content)
{
return mb_strlen($content, 'utf-8');
}
public function transLit($str)
{
return TranslitHelper::convert($str, LocaleHelper::getDefault());
}
/**
* Отчищает строку от лишних знаков для адреса url
*
* @param string $string
* @param bool $flag
*
* @return string
*/
public function urlClearFilter($string, $flag = true)
{
if ($flag) {
$s = ['(', ')', '&', '/', '\\', '`', '\'', '%', ',', '.', '#', '?', '"'];
} else {
$s = ['(', ')', '/', '\\', '`', '\'', '%', ',', '.', '#', '?', '"'];
}
$string = str_replace($s, '', $string);
return preg_replace('#[\s]#i', '-', trim($string));
}
/**
* Отчищает строку от лишних знаков для адреса url
*
* @param string $string
*
* @return string
*/
public function qChangeFilter($string)
{
return TranslitNameHelper::replacePrime($string, false);
}
/**
* Для пользовательских регулярных выражений в шаблонах
*
* @param string $string
* @param string|array $pattern строка или массив регулярных выражений
* @param string|array $replacement массив замены
*
* @return string
*/
public function pReplaceFilter($string, $pattern, $replacement)
{
return preg_replace($pattern, $replacement, $string);
}
/**
* Меняет большую гласную букву на маленькую с ударением
*
* @param string $str преобразуемая строка
*
* @return string
*/
public function emphasisFilter($str)
{
$str = preg_replace('#\s+#isUu', ' ', $str);
$words = explode(' ', $str);
$newWords = [];
foreach ($words as $word) {
preg_match_all('#[А-Я|A-Z]#u', $word, $matches);
$ch_str = '';
foreach (array_reverse($matches[0]) as $match) {
if (
in_array($match, [
'a',
'e',
'i',
'o',
'u',
'A',
'E',
'I',
'O',
'U',
'а',
'е',
'ё',
'и',
'о',
'у',
'э',
'ю',
'я',
'А',
'Е',
'Ё',
'И',
'О',
'У',
'Э',
'Ю',
'Я',
])
) {
$ch_str = str_replace($match, mb_convert_case($match, MB_CASE_LOWER, 'UTF-8') . '́', $word);
break;
}
}
if (empty($ch_str)) {
$ch_str = $word;
}
$newWords[] = $ch_str;
}
return mb_convert_case(implode(' ', $newWords), MB_CASE_LOWER, 'UTF-8');
}
/**
* @param DateTime $date
*
* @return string
*/
public static function dataLastFilter($date)
{
$now = date('d.m.y');
$yesterday = date('d.m.y', strtotime(date('Y-m-d')) - 3600 * 24);
switch ($date) {
case $date == $now:
$result = 'main_menu_today';
break;
case $date == $yesterday:
$result = 'main_menu_yesterday';
break;
default:
$result = false;
break;
}
return $result;
}
/**
* @param string $date
* @param string $p
*
* @return string
*/
public static function convertDate($date, $p)
{
return date($p, strtotime($date));
}
/**
* Функция обрезки текста по словам
*
* @param string $text - исходный текст
* @param int $length - максимальная длина получаемого текста
* @param bool $addDots
*
* @return string
*/
public static function cutTextForWords($text, $length, $addDots = false)
{
return StrHelper::cutText($text, $length, $addDots);
}
/**
* @param string $text
*
* @return string|string[]
*
* @throws Exception
*/
public function insertHolidays(string $text)
{
// Получаем строки выходных и сокращенных дней только один раз
if (!isset($this->holidaysString)) {
$calendarService = $this->container->get(CalendarService::class);
$this->holidaysString = $calendarService->getHolidaysString(CalendarHelper::HOLIDAY_TYPE);
}
if (!isset($this->halfHolidaysString)) {
$calendarService = $this->container->get(CalendarService::class);
$this->halfHolidaysString = $calendarService->getHolidaysString(CalendarHelper::HALF_HOLIDAY_TYPE);
}
$text = str_replace('%holidays%', $this->holidaysString, $text);
$text = str_replace('%half-holidays%', $this->halfHolidaysString, $text);
return $text;
}
/**
* Обработка текста перед выводом в блогах
*
* @param string $text - исходный текст
*
* @return string
*/
public static function convertText($text)
{
$out = str_replace([
'https://portal.treto.ru/portal.nsf/v0/',
'http://portal.treto.ru/portal.nsf/v0/',
'https://treto.ru/attach/v0/',
'http://treto.ru/attach/v0/',
'../v0',
], 'https://te.remote.team/v0/', $text);
$out = str_replace(['<iframe', '</iframe>'], ['<span class="blog-video-outer-wrapper"><span class="blog-video-inner-wrapper"><iframe', '</iframe></span></span>'], $out);
//<div class="blog-video-wrapper"></div>
//<p><br><iframe src="//www.youtube.com/embed/2TRNuSKglwc" width="854" height="510" frameborder="0"></iframe></p>
return $out;
}
/**
* @param DateTime $date
*
* @return string
*/
public static function friendlyDate($date)
{
if (empty($date)) {
return null;
}
$now = date('d.m.y');
if ($date->format('d.m.y') == $now) {
return $date->format('H:i');
} else {
return $date->format('d.m.y');
}
}
/**
* @param $num - число
* @param $words - массив падежей слова ([1], [2-4], [остальное])
*
* @return string
*/
public static function getCase($num, $words)
{
return TranslitHelper::getCase($num, $words);
}
/**
* @param string $text
* @param int $length
*
* @return string
*/
public static function separatorWord($text, $length = 20)
{
return wordwrap(str_replace(['~q~', '?'], ['\'', 'ø'], $text), $length, "\n", 1);
}
/**
* @param string $text
*
* @return string
*/
public static function uFirst($text)
{
$text = trim($text);
return mb_convert_case(mb_substr($text, 0, 1, 'UTF-8'), MB_CASE_UPPER, 'UTF-8') . mb_convert_case(mb_substr($text, 1, mb_strlen($text), 'UTF-8'), MB_CASE_LOWER, 'UTF-8');
}
/**
* @param string $text
*
* @return string
*/
public static function lFirst($text)
{
return mb_convert_case(mb_substr($text, 0, 1, 'UTF-8'), MB_CASE_LOWER, 'UTF-8') . mb_substr($text, 1, mb_strlen($text), 'UTF-8');
}
/**
* @param string $text
*
* @return string
*/
public static function uPrint($text)
{
return '<pre>' . print_r($text, true) . '</pre>';
}
public static function strSpaceless($value)
{
return preg_replace('/\s+/', '', $value);
}
/**
* @param array $interior
* @param string $type
*
* @return int
*/
public function interiorSizeTiny($interior, $type = 'x')
{
if ('x' == strtolower($type)) {
if ($interior['fileSizeZX'] && $interior['fileSizeZY']) {
return $interior['fileSizeZX'];
}
if ($interior['fileSizeX'] && $interior['fileSizeY']) {
return $interior['fileSizeX'];
}
if ($interior['fileSizeHDX'] && $interior['fileSizeHDY']) {
return $interior['fileSizeHDX'];
}
if ($interior['fileSizeSHDX'] && $interior['fileSizeSHDY']) {
return $interior['fileSizeSHDX'];
}
} elseif ('y' == strtolower($type)) {
if ($interior['fileSizeZX'] && $interior['fileSizeZY']) {
return $interior['fileSizeZY'];
}
if ($interior['fileSizeX'] && $interior['fileSizeY']) {
return $interior['fileSizeY'];
}
if ($interior['fileSizeHDX'] && $interior['fileSizeHDY']) {
return $interior['fileSizeHDY'];
}
if ($interior['fileSizeSHDX'] && $interior['fileSizeSHDY']) {
return $interior['fileSizeSHDY'];
}
}
return 0;
}
/**
* Строит путь до папки коллекции
*
* @param $collection
*
* @return string
*/
public function pathCollection($collection)
{
$path = '';
if (BiConst::CHOICE_ADDRESS_URL) {
if (!empty($collection['factory']['url']) && !empty($collection['url'])) {
$path = PathHelper::getImgWebPath() .
$collection['factory']['url'] . '/' . $collection['url'] .
'/' . BiConst::PER_SITO . '/';
}
} else {
if (!empty($collection['factory']['name']) && !empty($collection['name'])) {
$path = PathHelper::getImgWebPath() . rawurlencode(TranslitNameHelper::replacePrime($collection['factory']['name'], false)) . '/' . rawurlencode(TranslitNameHelper::replacePrime($collection['name'], false)) .
'/' . BiConst::PER_SITO . '/';
}
}
return $path;
}
public function prime($str)
{
return TranslitNameHelper::replacePrime($str, false);
}
/**
* @param $data
*
* @return string
*/
public function actualName($data)
{
if (is_array($data)) {
if (!empty($data['alternateName'])) {
return $data['alternateName'];
} else {
return $data['name'];
}
} else {
/* @var Factory $data */
return null != $data->getAlternateName() ? $data->getAlternateName() : $data->getName();
}
}
public function lessContent($text, $length, $lessText, $moreText)
{
$text = htmlspecialchars_decode($text);
if (mb_strlen(preg_replace('/<.*?>/', '', $text), 'UTF-8') <= $length) {
return $text;
}
$totalLength = 0;
$openTags = [];
$truncate = '';
preg_match_all('/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER);
foreach ($tags as $tag) {
if (!preg_match('/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2])) {
if (preg_match('/<[\w]+[^>]*>/s', $tag[0])) {
array_unshift($openTags, $tag[2]);
} else {
if (preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag)) {
$pos = array_search($closeTag[1], $openTags);
if (false !== $pos) {
array_splice($openTags, $pos, 1);
}
}
}
}
$truncate .= $tag[1];
$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');
if ($contentLength + $totalLength > $length) {
$left = $length - $totalLength;
$entitiesLength = 0;
if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE)) {
foreach ($entities[0] as $entity) {
if ($entity[1] + 1 - $entitiesLength <= $left) {
--$left;
$entitiesLength += mb_strlen($entity[0], 'UTF-8');
} else {
break;
}
}
}
$truncate .= mb_substr($tag[3], 0, $left + $entitiesLength, 'UTF-8');
break;
} else {
$truncate .= $tag[3];
$totalLength += $contentLength;
}
if ($totalLength >= $length) {
break;
}
}
$truncate .= '...';
foreach ($openTags as $tag) {
$truncate .= '</' . $tag . '>';
}
return '<div class="content-less">' . $truncate . '</div>' .
'<div class="content-full">' . $text . '</div>' .
'<a class="content-more-link" rel="nofollow" data-action="open"' .
' data-more-up="' . $lessText . '"' .
' data-more-down="' . $moreText . '">' .
$moreText . '</a>';
}
public function transform($text)
{
return TranslitNameHelper::replacePrime($text, false);
}
public function replaceUmlautChar($text)
{
return StrHelper::replaceUmlautChar($text);
}
public function decodeHtml($str)
{
return htmlspecialchars_decode($str);
}
/**
* @param $str
* @param $needle
* @param int $offset
*
* @return bool|int
*/
public function strPos($str, $needle, $offset = 0)
{
return strpos($str, $needle, $offset);
}
/**
* Функция возврата количества символов в дробной части числа
*
* @param $str
*
* @return int
*/
public function getFractPartLength($str)
{
$result = 0;
$str = str_replace(',', '.', $str);
if (strpos($str, '.')) {
$fractPart = explode('.', $str);
$result = strlen($fractPart[1]);
}
return $result;
}
/**
* @param $text
*
* @return string
*/
public static function getShortFio($text)
{
$fio = explode(' ', $text);
$c = count($fio);
if ($c < 2) {
return $text;
}
// mb_internal_encoding("UTF-8");
$newFio = [];
foreach ($fio as $key => $n) {
if ($key > 0) {
$n = mb_substr($n, 0, 1, 'UTF-8') . '.';
}
$newFio[] = $n;
}
return implode(' ', $newFio);
}
/**
* @param $imagePath
*
* @return string
*
* @throws ImagickException
*/
public function makeThumbnail($imagePath)
{
//try {
$whitelist = [
'127.0.0.1',
'::1',
];
//$imageClearPath = htmlentities($imagePath);
$remoteAddr = $_SERVER['REMOTE_ADDR'];
$docRoot = $_SERVER['DOCUMENT_ROOT'];
if (strrpos($docRoot, 'https://tile.expert') || in_array($remoteAddr, $whitelist)) {
$newImg = explode('/', $imagePath);
$newImg = urldecode($newImg[count($newImg) - 1]);
if (!is_dir($docRoot . '/media/cache/slide-show/')) {
mkdir($docRoot . '/media/cache/slide-show/', 0777);
}
if (!file_exists($docRoot . '/media/cache/slide-show/' . $newImg)) {
if (in_array($remoteAddr, $whitelist)) {
$imgSrc = $docRoot . '/media/cache/slide-show/new-' . $newImg;
copy($imagePath, $imgSrc);
} else {
$imgSrc = $imagePath;
}
$image = new Imagick($imgSrc);
$image->thumbnailImage(110, 110);
$image->writeImage($docRoot . '/media/cache/slide-show/' . $newImg);
}
return '/media/cache/slide-show/' . $newImg;
} else {
return $imagePath;
}
/*} catch(Exception $e) {
echo 'Exception: ', $e->getMessage(), "n";
}*/
}
/**
* @param $str
* @param $data
* @param null $number
* @param int $sex
* @param null $bankTransfer
*
* @return mixed
*
* @throws Exception
*/
public function setDataHistoryOrder($str, $data, $number = null, $sex = 1, $bankTransfer = null)
{
$mask = [
'%table%' => '',
'%table2%' => '',
'%tableForReview%' => '',
'%managerName%' => '',
'%managerEmail%' => '',
'%managerPhone%' => '',
];
if (!empty($number)) {
$mask['%number%'] = '<a href="#">' . $number . '</a>';
}
unset($data['country']);
if (isset($data['%lift%'])) {
$data['%lift%'] = App::trans($data['%lift%'], App::getCurLocale());
}
$data['%link%'] = '#';
$data['%acceptLink%'] = '#confirmTheDateBlock';
$data['%setDateLink%'] = '#confirmTheDateBlock';
$data['%cancelLink%'] = '#confirmTheDateBlock';
$data['%designLinkLeft%'] = '';
$data['%designLinkRight%'] = '';
$data['%designFooterStart%'] = '';
$data['%designFooterEnd%'] = '';
$data['%bankTransfer%'] = $bankTransfer ? App::trans('var_bank_transfer') : '';
if (!empty($data['%sysPayment%'])) {
$data['%sysPayment%'] = App::trans($data['%sysPayment%'], App::getCurLocale());
}
if (!empty($data['%sysPayment2%'])) {
$data['%sysPayment2%'] = App::trans($data['%sysPayment2%'], App::getCurLocale());
}
if (empty($data['%offsetDate2%'])) {
$data['%offsetDate2%'] = App::trans('buyOrder.offsetData_2', App::getCurLocale());
$data['%OffsetDate2%'] = StrHelper::ucFirstOnly($data['%offsetDate2%']);
}
$data['%fio%'] = $data['%fio%'] ?? '';
$t = App::trans((1 == $sex ? 'title.man' : 'title.woman'), App::getCurLocale());
if ('fr' != App::getCurLocale()) {
$data['%fio%'] = $t . ' ' . $data['%fio%'];
} else {
$data['%fio%'] = $t;
}
$data['%fio%'] .= App::getCurLocale() ? '!' : ',';
$data = array_merge($mask, $data);
$dataKey = array_keys($data);
$data = array_values($data);
// получаем необходимое письма и подставляем переменные
return str_replace($dataKey, $data, $str);
}
/**
* @param DateTime $date
*
* @return mixed
*
* @throws Exception
*/
public function convertToHours($date)
{
$d = new DateTime();
return $d->diff($date)->format('%d') * 24;
}
/**
* @param Article $article
* @param array $param
*
* @return string
*
* @throws Exception
*/
public function price($article, $param = [])
{
return LocaleHelper::getPrice($article, $param);
}
/**
* @param ArticlePriceDiscount $priceDiscount
* @param array $param
*
* @return array
*
* @throws Exception
*/
public function priceDiscount($priceDiscount, $param = [])
{
return LocaleHelper::getPriceDiscount($priceDiscount, $param);
}
/**
* @param Article $article
* @param array $param
*
* @return string
*
* @throws Exception
*/
public function priceMq($article, $param = [])
{
return LocaleHelper::getPriceMq($article, $param);
}
/**
* @param Article $article
* @param array $param
* @param int $type
*
* @return string
*
* @throws Exception
*/
public function measure($article, $param = [], $type = 1)
{
return LocaleHelper::getMeasure($article, $param, $type);
}
/**
* @param $val
* @param int $type
*
* @return float
*/
public function convertFt($val, $type = 1): float
{
return ConversionHelper::convertFt((float) $val, $type);
}
/**
* @param $val
* @param int $type
*
* @return float
*/
public function convertSqFt($val, $type = 1): float
{
return ConversionHelper::convertSqFt((float) $val, $type);
}
/**
* @param $val
* @param int $type
*
* @return float
*/
public function convertKgLb($val, $type = 1): float
{
return ConversionHelper::convertKgLb((float) $val, $type);
}
/**
* @param $str
* @return string
* @throws Exception
*/
public function currency($str = null)
{
return LocaleHelper::getCurrency($str);
}
/**
* @param BuyOrder $order
* @return array
* @throws Exception
*/
public function orderSum(BuyOrder $order)
{
return OrderHelper::sum($order);
}
/**
* @param BuyOrderArticle $item
* @param BuyOrder $order
* @return bool
*/
public function availabilityItemOrder(BuyOrderArticle $item, BuyOrder $order)
{
$specPrice = $order->getSpecPrice();
$orderStatusId = $order->getStatus();
return OrderHelper::availabilityItemOrder($item, $specPrice, $orderStatusId);
}
/**
* @param BuyOrder $order
* @return float
* @throws Exception
*/
public function deliveryWVat(BuyOrder $order)
{
return OrderHelper::deliveryWVat($order);
}
/**
* @param BuyOrder $order
* @return bool
* @throws Exception
*/
public function asVat(BuyOrder $order)
{
return OrderHelper::asVat($order);
}
/**
* @param BuyOrder $order
* @return bool
* @throws Exception
*/
public function homeCountryVat(BuyOrder $order)
{
return OrderHelper::homeCountryVat($order);
}
/**
* @param Article $article
* @param array $param
* @param int $type
*
* @return string
*
* @throws Exception
*/
public function packagingCount($article, $param = [], $type = 1)
{
return LocaleHelper::getPackagingCount($article, $param, $type);
}
/**
* @param Article $article
* @param array $param
*
* @return string
*
* @throws Exception
*/
public function pallet($article, $param = [])
{
return LocaleHelper::getPallet($article, $param);
}
/**
* @param Article $article
* @param float|null $amount
* @param array $param
* @param int $type
*
* @return string
*
* @throws Exception
*/
public function amount($article, $amount = null, $param = [], $type = 1)
{
return LocaleHelper::getAmount($article, $amount, $param, $type);
}
/**
* @param Article $article
* @param array $param
*
* @return string
*
* @throws Exception
*/
public function weight($article, $param = [])
{
return LocaleHelper::getWeight($article, $param);
}
/**
* @param float|null $weight
* @param bool $with
* @param BuyOrder|null $order
*
* @return string
*
* @throws Exception
*/
public function weightLabel(?float $weight = 1.0, bool $with = true, ?string $measure = null): string
{
return LocaleHelper::weightLabel($weight, $with, $measure);
}
/**
* @param array $param
*
* @return bool
*
* @throws Exception
*/
public function measureGb($param = [])
{
return LocaleHelper::measureGb($param);
}
/**
* @param $orderItem
*
* @return string
*
* @throws Exception
*/
public function orderItemTime(BuyOrderArticle $orderItem): string
{
return OrderItemHelper::getItemTime($orderItem);
}
/**
* @param int $type
* @param null $country
*
* @return string
*
* @throws Exception
*/
public function dateMask($type = 1, $country = null)
{
return LocaleHelper::dateMask($type, $country);
}
/**
* @return mixed|string|null
*
* @throws Exception
*/
public function userCurrency()
{
return LocaleHelper::getCur();
}
/**
* @throws Exception
*/
public function userGA()
{
return CookieHelper::get('_ga');
}
/**
* @return string
*
* @throws Exception
*/
public function userCountry()
{
return App::getCurCountry();
}
/**
* @return string|null
*
* @throws Exception
*/
public function userMeasure()
{
return LocaleHelper::getUserMeasure();
}
/**
* @param array $params
*
* @return bool
*
* @throws Exception
*/
public function curLimit($params = [])
{
return LocaleHelper::getCurLimit($params);
}
/**
* @return string
*
* @throws Exception
*/
public function curLimitEx()
{
return LocaleHelper::getCurLimitEx();
}
/**
* Конвертация в дюймы
*
* @param float $val
* @param int $type 1 - мм, 0 - inch
*
* @return float
*/
public function convertInch($val, $type = 1): float
{
return ConversionHelper::convertInch((float) $val, $type);
}
/**
* Возвращает минимальное ограничение по заказу
*
* @param array $param
*
* @return int
*
* @throws Exception
*/
public function curLimitVal($param = [])
{
return LocaleHelper::getCurLimitVal($param);
}
/**
* Определяет летнее/зимнее время по Лондону
*
* @return bool
*/
public function typeTime()
{
$old = date_default_timezone_get();
date_default_timezone_set('Europe/London');
$ts = time();
$dy = date('I', $ts);
date_default_timezone_set($old);
if (1 == $dy) {
return (string) '1';
} else {
return (string) '0';
}
}
/**
* @param $string
*
* @return mixed
*/
public function replaceSymbolsTitleFilter($string)
{
return TranslitHelper::replaceSymbolsTitleFilter($string);
}
/**
* @param string $price
*
* @return mixed
*/
public function wrapCents($price)
{
$price = (string) $price;
$sign = '.';
if (!strpos($price, $sign)) {
$sign = ',';
}
if (2 == count(explode($sign, $price))) {
return str_replace($sign, $sign . '<span class="top-aligned-cents">', $price) . '</span>';
} else {
return $price;
}
}
/**
* @param $coll
* @param array $param
*
* @return mixed
*
* @throws Exception
*/
public function prMin($coll, $param = [])
{
return LocaleHelper::getPrMin($coll, $param);
}
/**
* @param string $type ['collection'|'article'|'factory'|'publication']
* @param array|object $data
*
* @return mixed
*/
public function pathGenerate($type, $data)
{
return PathHelper::pathGenerate($type, $data);
}
/**
* получить координаты бирки
*
* @param $article
* @param $interior
*
* @return mixed
*
* @throws DBALException
*/
public function getCoords($article, $interior)
{
return SliderHelper::getCoords($article, $interior);
}
/**
* возвращает является ли артикул заглавным в интерьере
*
* @param $article
* @param $interior
*
* @return mixed
*
* @throws DBALException
*/
public function getInteriorHead($article, $interior)
{
return SliderHelper::getInteriorHead($article, $interior);
}
public function timestamp()
{
return strtotime('now') + 5000;
}
/**
* @param bool $full !deprecated
*
* @return string
*/
public function getCurLocale($full = false)
{
return App::getCurLocale($full);
}
/**
* @param bool $full
*
* @return string
*/
public function userLocale($full = false)
{
return App::getCurLocale($full);
}
/**
* Меняет точку на запятую в дробных значениях для стран где принят такой формат
*
* @param float $val
* @param int $decimals
* @param bool $float если true то вернёт цифровое значение
*
* @return mixed
*/
public function floatSing($val, $decimals = 2, $float = false)
{
return LocaleHelper::floatSign($val, $decimals, $float);
}
public function bcdiv($val, $decimals = 2)
{
return bcdiv($val, 1, $decimals);
}
/**
* Меняет точку на запятую в дробных значениях для стран где принят такой формат;
* для 3 знаков после запятой
*
* @param float $val
* @param int $decimals
* @param bool $float если true то вернёт цифровое значение
*
* @return mixed
*/
public function floatSingDec($val, $decimals = 3, $float = false)
{
return LocaleHelper::floatSign($val, $decimals, $float);
}
/**
* Удаляет дробную часть числа
*
* @param float $val
*
* @return int
*/
public function removeDec($val)
{
return round($val, 0);
}
/**
* вывод атрибутов в шаблоне
*
* @param array $attributes
*
* @return int
*/
public function showAttributes($attributes)
{
$name = [];
$locale = App::getCurLocale();
foreach ($attributes as $key => $attribute) {
$a = is_object($attribute) ? $attribute->getAlias() : $attribute['alias'];
$alias = $this->translator->trans($a);
if ($key > 0) {
if ('de' == $locale) {
$alias = TranslitHelper::replaceAttributesTitle($alias);
} elseif ('left_menu_3d' == $a) {
$alias = mb_strtoupper(TranslitHelper::replaceAttributesTitle($alias));
} else {
$alias = mb_strtolower(TranslitHelper::replaceAttributesTitle($alias));
}
}
$name[] = trim($alias);
}
return implode(', ', $name);
}
/**
* вывод атрибутов style в шаблоне
*
* @param $attributes
*
* @return mixed
*/
public function showStyleAttributes($attributes)
{
$name = [];
$locale = App::getCurLocale();
/* @var ListStyle $style */
if ('en' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} elseif ('it' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} elseif ('es' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} elseif ('fr' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} elseif ('de' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
$output = ucfirst(implode(', ', $name));
} elseif ('pl' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} elseif ('nl' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} elseif ('fi' == $locale) {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
} else {
$count = is_object($attributes) ? count($attributes->count()) : count($attributes);
foreach ($attributes as $key => $style) {
$a = is_object($style) ? $style->getAlias() : $style['alias'];
$alias = $this->translator->trans($a);
$alias = $count > 1 ? mb_strtolower(TranslitHelper::replaceAttributesTitle($alias)) : mb_strtolower($alias);
$name[] = trim($alias);
}
if ($count > 1) {
$output = ucfirst(mb_strtolower($this->translator->trans('left_menu_style')) . ': ' . implode(', ', $name));
} else {
$output = ucfirst(implode(', ', $name));
}
}
return $output;
}
/**
* @param $str
*
* @return string
*/
public static function symbolCyrillicUnderline($str)
{
return TranslitNameHelper::returnStrCyrillicSymbolUnderline($str);
}
public function lenThanSomeSymbol($str)
{
return TranslitNameHelper::lenThanSomeSymbol($str);
}
/**
* @param $date
*
* @return mixed|string
*/
public static function humanData($date)
{
return HumanDataHelper::get((int) $date);
}
public function isEmployee(?string $email): bool
{
return UserHelper::isEmployee($email);
}
/**
* @param ?int $type
* @param ?string $locale
*
* @return array
*
* @throws Exception
*/
public static function humanSampleType(?int $type = 1, ?string $locale = null): array
{
return OrderItemHelper::humanSampleType($type, $locale);
}
/**
* @param BuyOrderArticle|array $article
* @param array $params
* @param bool $inch
* @param null $locale
*
* @return string
*
* @throws Exception
*/
public static function sampleFormat($article, $params, $inch = false, $locale = null)
{
return OrderItemHelper::sampleFormat($article, $params, $inch, $locale);
}
/**
* @param $order
* @param bool $withLimit
* @return bool
* @throws Exception
*/
public static function readyCreate($order, $withLimit = true)
{
return OrderHelper::readyCreate($order, $withLimit);
}
/**
* @param $order
* @param bool $withLimit
* @return bool
* @throws Exception
*/
public static function checkForSend($order, $withLimit = true)
{
return OrderHelper::checkForSend($order, $withLimit);
}
/**
* @return bool
*
* @throws Exception
*/
public static function isWithoutVATPrice()
{
return false !== LocaleHelper::isWithoutVATPrice(10);
}
/**
* @throws Exception
*/
public static function includeVATAlways(): float
{
return LocaleHelper::includeVATAlways();
}
/**
* @return array
*/
public static function baseProps()
{
return [
'baseUrl' => /*App::getRequest()->getSchemeAndHttpHost() . */ App::getRequest()->getBaseUrl(),
'locale' => App::getCurLocale(true),
'lang' => App::getCurLocale(),
];
}
public static function vatRequiredState(BuyOrder $order): bool
{
if ($order->getDeliveryCountry()) {
$country = strtolower($order->getDeliveryCountry()->getCode());
} else {
$country = 'at';
}
return in_array($country, OrderHelper::vatRequired()['char']);
}
/**
* @param BuyOrder $order
* @return int
* @throws Exception
*/
public static function orderPercent(BuyOrder $order)
{
return OrderHelper::vatPercent($order);
}
/**
* @param BuyOrder $order
* @return string
* @throws Exception
*/
public static function orderVatText(BuyOrder $order)
{
return OrderHelper::vatText($order);
}
public static function orderMsg(BuyOrder $order)
{
return OrderHelper::msg($order);
}
/**
* @param int $orderId
* @return string
*/
public static function orderStatusAliasByStatusId(int $orderId): string
{
return BuyOrderStatusEnum::from($orderId)->getAlias();
}
/**
* @param BuyOrder $order
* @param int|bool $flag
* @return float|int
* @throws Exception
*/
public static function paymentPercent(BuyOrder $order, $flag = false)
{
return OrderHelper::paymentPercent($order, $flag);
}
/**
* @param $val
* @param $percent
* @param bool $type
* @return float
*/
public function getPercent($val, $percent, $type = true)
{
return OrderHelper::percent($val, $percent, $type);
}
/**
* @param BuyOrder $order
* @return array
* @throws Exception
*/
public function orderParams(BuyOrder $order)
{
return OrderHelper::params($order);
}
/**
* @param BuyOrder $order
* @return float|int
* @throws Exception
*/
public function vatFactor(BuyOrder $order)
{
return OrderHelper::vatFactor(OrderHelper::vatPercent($order));
}
/**
* @param BuyOrder $order
* @return bool
*/
public function isHoliday(BuyOrder $order)
{
return OrderHelper::isHoliday($order);
}
/**
* @param BuyOrder $order
* @param bool $euro
* @return float
*/
public function totalSum(BuyOrder $order, $euro = false)
{
return OrderHelper::totalSum($order, $euro);
}
/**
* @param BuyOrder $order
* @return bool
* @throws Exception
*/
public function statePaymentButton(BuyOrder $order)
{
return OrderHelper::statePaymentButton($order);
}
/**
* @param BuyOrder $order
* @return bool
* @throws Exception
*/
public function onlySamples(BuyOrder $order)
{
return OrderHelper::onlySamples($order);
}
/**
* @param BuyOrder $order
* @return bool
*/
public function noVat(BuyOrder $order): bool
{
return OrderHelper::noVat($order);
}
public function cmToInch($val): float
{
if (is_numeric($val)) {
return ConversionHelper::convertInch((float) $val, ConversionHelper::CM);
}
return 0;
}
public function resolverScriptSize($item): string
{
if (is_array($item)) {
if (!empty($item['shape']) && $item['shape'] == 7) {
return 'L';
} else {
return '⌀';
}
} elseif ($item->getShape() && $item->getShape()->getId() == 7) {
return 'L';
} else {
return '⌀';
}
}
public function getUnreadCount(): int
{
$token = UserHelper::getInstance()->getToken();
$chat = $this->chatBRepository->findOneBy(['token' => $token]);
if ($chat) {
return $this->chatBMessageRepository->getUnreadMessagesCountForChat($chat);
}
return 0;
}
public function getJwt(): string
{
$token = UserHelper::getInstance()->getToken();
return $this->jwtGenerator->generateJWT($token);
}
public function getUserChannel(): string
{
$token = UserHelper::getInstance()->getToken();
return "general#$token";
}
public function useRTWidget(): bool
{
$setting = $this->boolDBSettingRepository->findOneByName('RTWidget');
if (null === $setting) {
return false;
}
return $setting->getVal();
}
/**
* @throws Exception
*/
public function getWidgetId(): string
{
$lang = App::getCurLocale(false);
$widget = $this->widgetRepository->findOneBy(['lang' => $lang]);
if (!$widget) {
throw new Exception(sprintf('Для языка "%s" не заведен виджет в базе данных', $lang));
}
return $widget->getWidgetId();
}
/**
* Для испанских клиентов делаем возможность платить Visa, MasterCard, Maestro через Адиен
* Все остальные - через БрайнТри
*/
public function getUrlForPaymentByVisa(BuyOrder $order): string
{
if (OrderHelper::country($order) === CountryNumberEnum::ES) {
return $this->urlGenerator->generate('app_credit_card_form_old', ['hash' => $order->getHash()]);
}
return $this->urlGenerator->generate('app_credit_card_form', ['hash' => $order->getHash()]);
}
/**
* Для испанских клиентов делаем возможность платить Amex через Адиен
* Для валют, кроме евро, долларов и фунтов платить Amex через Адиен
* Все остальные - платить Amex через БрайнТри
*/
public function getUrlForPaymentByAmex(BuyOrder $order): string
{
if (OrderHelper::country($order) === CountryNumberEnum::ES) {
return $this->urlGenerator->generate('app_credit_card_form_old', ['hash' => $order->getHash()]);
}
if (OrderHelper::availableAdyenAmex($order)) {
return $this->urlGenerator->generate('app_credit_card_form_old', ['hash' => $order->getHash()]);
}
return $this->urlGenerator->generate('app_credit_card_form', ['hash' => $order->getHash()]);
}
}