<?php
namespace WebBundle\Service;
use AdmBundle\Helper\StrAdm;
use Exception;
use FlexApp\Constant\TimeConstant;
use FlexApp\Entity\CommentEntity;
use FlexApp\Service\LastUrlService;
use FlexApp\Service\RedisCachePool;
use Import1CBundle\Helper\v3\BiConst;
use Import1CBundle\Helper\v3\TranslitNameHelper;
use Monolog\Logger;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use WebBundle\Entity\Article;
use WebBundle\Entity\Collection;
use WebBundle\Entity\FilterEntity;
use WebBundle\Helper\App;
use WebBundle\Helper\ArrHelper;
use WebBundle\Helper\FilterHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\PathHelper;
use WebBundle\Helper\StrHelper;
use WebBundle\Helper\TranslitHelper;
use WebBundle\Helper\UserHelper;
use WebBundle\Repository\ArticleRepository;
use WebBundle\Repository\CollectionRepository;
use WebBundle\Repository\FilterRepository;
use WebBundle\Repository\InteriorRepository;
class CollectionService extends ExtendService
{
/** @required */
public LastUrlService $lastUrlService;
/** @required */
public CollectionRepository $collectionRepository;
/** @required */
public FilterRepository $filterRepository;
/** @required */
public FiltersService $filtersService;
/** @var Request $oRequest */
protected $oRequest;
/** @var Session $oSession */
protected $oSession;
/** Текущая локаль запроса */
protected string $sLocale;
private Logger $oLogger;
private array $readySettings = [];
public function __construct(Logger $logger)
{
$this->oSession = App::getContainer()->get('session');
$this->oRequest = App::getRequest();
$this->sLocale = $this->oRequest->getLocale();
$this->oLogger = $logger;
}
/**
* @param string $unid
* @return array
* @throws Exception
*/
public function getCommentsCountData(string $unid): array
{
$commentRepo = App::em()->getRepository(CommentEntity::class);
return [
'questions' => $commentRepo->getCommentCountData($unid, App::getCurLocale(), false),
'answers' => $commentRepo->getCommentCountData($unid, App::getCurLocale())
];
}
/**
* Залипуха, что бы количество коллекций было одинаковым в разных местах, если нет фильтрации
* @return int
* @throws Exception
*/
public function countNotFilteredCollection(): int
{
$redisCachePool = App::getContainer()->get(RedisCachePool::class)->getPool();
$memKey = 'collection_count_not_filtered'. App::getCurCountry(); //ну как же без учета страны?
$cntItem = $redisCachePool->getItem($memKey);
if (!$cntItem->isHit()) {
$data = [
'searchFilter' => [],
'searchSort' => 1,
'searchPeriod' => null,
'locale' => App::getCurLocale(),
];
$aRes = App::searchSphinx($data, 300, false);
$cnt = count($aRes);
$cntItem->set($cnt);
$cntItem->expiresAfter(86400);
$redisCachePool->save($cntItem);
}else{
$cnt=$cntItem->get();
}
return (int)$cnt;
}
/**
* @param $coll
* @param bool $flag
* @param string $format
* @param null $locale
* @return array|Response|null
* @throws Exception
*/
public function settingsListAction($coll, bool $flag = false, string $format = 'html', $locale = null)
{
$settings = [];
$marker = [];
$offShade = [];
$sliding = [];
$nonSlip = false;
$authorLink = false;
$locale = $locale ? $locale : App::getCurLocale();
/** @var ArticleRepository $repoArticle */
$repoArticle = App::getRepository('WebBundle:Article');
/** @var InteriorRepository $repoInterior */
$repoInterior = App::getRepository('WebBundle:Interior');
/** @var $collectionRepository CollectionRepository */
$collectionRepository = App::getRepository('WebBundle:Collection');
if (is_array($coll)) {
$collection = $coll;
$collectionAuthor = $collection['author'];
$collection['interiors'] = $repoInterior->getInteriorsByCollection($coll['id']);
$collection['articles'] = $repoArticle->getArticleByCollection($coll['id']);
$exhibitions = !empty($collection['exhibition']) ? $collection['exhibition'] : [];
} else {
$collection['articles'] = $repoArticle->getArticleByCollection($coll);
$collection['interiors'] = $repoInterior->getInteriorsByCollection($coll);
/** @var Collection $collection */
$collectionAuthor = $collectionRepository->getCollAuthor($coll);
$exhibitions = $collection->getExhibition()->toArray();
}
// приводим дизайнеров к массиву
if ($collectionAuthor and !is_array($collectionAuthor)) {
$collectionAuthor = explode(',', $collectionAuthor);
$collectionAuthor = array_map('trim', $collectionAuthor);
$collectionAuthor = array_diff($collectionAuthor, ['']);
}
// смотрим интерьеры если accessible не TRUE
if (!$collection['accessible']) {
foreach ($collection['interiors'] as $interior) {
if (!empty($interior['applies'])) {
$settings = $this->parseFiltersForSettings($interior['applies'], $settings, 'getUsings', $collectionAuthor);
}
if (!empty($interior['styles'])) {
$settings = $this->parseFiltersForSettings($interior['styles'], $settings, 'getStyles', $collectionAuthor);
}
if (!empty($interior['textures'])) {
foreach ($interior['textures'] as $i => $texture) {
if ($texture['alias'] == 'left_menu_mono_color') {
$settings = $this->parseFiltersForSettings($texture, $settings, 'getColors', $collectionAuthor);
} else {
$settings = $this->parseFiltersForSettings($texture, $settings, 'getFacturas', $collectionAuthor);
}
}
}
}
}
/** @var Article|array $article */
foreach ($collection['articles'] as $article) {
// /en/tile/Serenissima-Cir/Marble-Style
if (!empty($article['pei'])) {
$settings = $this->parseFiltersForSettings($article, $settings, 'Pei', $collectionAuthor);
}
if (!empty($article['style'])) {
$settings = $this->parseFiltersForSettings($article['style'], $settings, 'getStyles', $collectionAuthor);
}
if (!empty($article['type']) && $article['type']['id'] == 24) {
$article['type']['name'] = App::getTranslator()->trans($article['type']['alias']);
$settings = $this->parseFiltersForSettings($article['type'], $settings, 'getType', $collectionAuthor);
}
if (!empty($article['material'])) {
if ($article['thinGranite'] == 1) {
$article['material']['name'] = App::getTranslator()->trans('left_menu_thin_porcelain_tile');
} else {
$article['material']['name'] = App::getTranslator()->trans($article['material']['alias']);
}
$settings = $this->parseFiltersForSettings($article['material'], $settings, 'getMaterials', $collectionAuthor);
}
// пока так сделал.
if (!empty($article['using']) && $article['using']['hide'] == 0) {
$name = $locale != 'de' ?
mb_convert_case(App::getTranslator()->trans($article['using']['alias']), MB_CASE_LOWER, "UTF-8") :
App::getTranslator()->trans($article['using']['alias']);
$code = FilterHelper::normaliseAltName($name);
$searchLink = $name;
$searchLink = str_replace([' ', '-'], '_', StrHelper::toLower($searchLink));
$link = FilterHelper::getUrl($searchLink, $locale);
$val = [
'name' => $name,
'link' => $this->fixLink($link),
];
if (empty($settings['getTypeUsings']) || (!in_array(
$val,
$settings['getTypeUsings']
) && ($article['using']['id'] == 4 || !in_array(4, $marker['getTypeUsings'])))
) {
if ($article['using']['id'] == 4) {
$settings['getTypeUsings'][$article['using']['alias']] = $val;
$marker['getTypeUsings'][$code] = $article['using']['id'];
} else {
$settings['getTypeUsings'][$article['using']['alias']] = $val;
$marker['getTypeUsings'][$code] = $article['using']['id'];
}
}
}
if (!empty($article['surface'])) {
if ($article['surface']['id'] == 8) {
$article['surface']['name'] = App::getTranslator()->trans('catalog.options.non_slip');
} else {
$article['surface']['name'] = App::getTranslator()->trans($article['surface']['alias']);
}
$settings = $this->parseFiltersForSettings($article['surface'], $settings, 'getSurfaces', $collectionAuthor);
if ($article['surface']['id'] == 8) {
$name = App::getTranslator()->trans($article['surface']['alias']);
$nonSlip = FilterHelper::normaliseAltName($name);
}
}
if (!empty($article['textures'])) {
foreach ($article['textures'] as $i => $texture) {
if ($texture['alias'] == 'left_menu_mono_color') {
$settings = $this->parseFiltersForSettings($texture, $settings, 'getColors', $collectionAuthor);
} else {
$settings = $this->parseFiltersForSettings($texture, $settings, 'getFacturas', $collectionAuthor);
}
}
}
if (!empty($article['edgeType'])) {
$settings = $this->parseFiltersForSettings($article['edgeType'], $settings, 'getEdgeType', $collectionAuthor);
}
if (!empty($article['sliding']) && !empty($article['sliding']['id'])) {
$elem = [
'name' => 'R' . $article['sliding']['id'],
'title' => App::getTranslator()->trans(
'catalog.options.non_slip_rating',
['%d%' => 'R' . $article['sliding']['id']]
),
];
if (!in_array($elem, $sliding)) {
$sliding[] = $elem;
}
}
if (!empty($article['offShade'])) {
if (!in_array('V' . $article['offShade']['id'], $offShade)) {
$offShade[] = 'V' . $article['offShade']['id'];
}
}
}
if (!empty($settings['getStylesDesigners']) and !empty($settings['getStyles'])) {
unset($settings['getStyles']['left_menu_designer']);
if (isset($settings['getStyles'])) {
unset($settings['getStyles']);
}
}
if ($nonSlip !== false) {
$settings['getSurfaces'][$nonSlip]['list'] = $sliding;
}
if (count($offShade) > 0) {
$nm = App::getTranslator()->trans('catalog.options.shade_variation', ['%d%' => implode(', ', $offShade)]);
$settings['offShade'][] = [
'name' => App::getCurCountry() != 'de' ? StrHelper::lcFirstOnly($nm) : StrHelper::ucFirstOnly($nm),
'link' => null,
];
}
if (empty($settings['getEdgeType'])) {
$name = App::getTranslator()->trans('left_menu_no_retified');
$code = FilterHelper::normaliseAltName($name);
$link = FilterHelper::getUrl(str_replace([' ', '-'], '_', StrHelper::toLower($name)));
$val = [
'name' => $name,
'link' => $this->fixLink($link),
];
$settings['getEdgeType'][$code] = $val;
}
if (!empty($settings['getSurfaces'])) {
$surfaceList = ArrHelper::get($settings, 'getSurfaces.antislip_surface.list');
if (!empty($settings['getSurfaces']['left_menu_antislip']) and $surfaceList) {
unset($settings['getSurfaces']['antislip_surface']);
$settings['getSurfaces']['left_menu_antislip']['list'] = $surfaceList;
}
}
// перенес дизайнеров в конец, что бы перечислением хоть как то адекватно вписалось к остальным свойствам
if (!empty($settings['getStylesDesigners'])) {
$designers = $settings['getStylesDesigners'];
unset($settings['getStylesDesigners']);
$settings['getStylesDesigners'] = $designers;
}
$rankService = App::getContainer()->get('app.service.rank');
if ($exhibitions) {
$exhibitions = array_values($this->filterRepository->getExhibitions($collection['exhibition']));
foreach ($exhibitions as $i => $e) {
$r = [
'name' => $e['name'],
'title' => $e['tooltip'],
'link' => $e['urlLocal'],
'nameGroup' => 'exhibition',
'rank' => 0,
];
$exhibitions[$i] = $r;
}
// добавляем хитро в начало
$settings = array_reverse($settings, true);
$settings['exhibitions'] = $exhibitions;
$settings = array_reverse($settings, true);
}
$settingsJoin = [];
foreach ($settings as $k => $row) {
// выстраиваем в ряд значения PEI, если их больше одного
if ($k == 'Pei' && count($row) > 1) {
$pei = ['name' => 'PEI '];
foreach ($row as $item) {
$pei['name'] = $pei['name'] . trim(str_replace('PEI', '', $item['name'])) . ', ';
$pei['link'] = $this->fixLink($item['link']);
$pei['title'] = $item['title'];
$pei['noLower'] = $item['noLower'];
}
$pei['name'] = trim(trim($pei['name']), ',');
$row = ['pei' => $pei];
}
foreach ($row as $i => $item) {
$rank = ArrHelper::get($item, 'rank', 0);
$row[$i]['rank'] = $rank;
$row[$i]['size'] = $rankService->fontSizeByRank($rank);
}
$settingsJoin = array_merge($settingsJoin, $row);
}
// формируем размеры под свойства на основании RANK
//////////////////////////////////////////////////////////////
$rankArr = [];
foreach ($settingsJoin as $k => $row) {
// задаем значение для сортировки
$rankArr[$k] = $row['rank'];
}
$settingsSorting = $settingsJoin;
array_multisort($rankArr, SORT_DESC, $settingsSorting);
// Формируем пороги для выделения размеров, выделяем первые две четверти
$cnt = count($settingsJoin);
// количество выделяемых в четверти
$cnt = (int)ceil($cnt / 4);
$i = 0;
foreach ($settingsSorting as $key => $row) {
if (StrHelper::isInStr($key, 'pei_') or $key == 'antislip_surface' or !$key) {
$settingsJoin[$key]['size'] = $rankService->fontSizeByRank(50);
} else {
$i++;
if ($i <= $cnt) {
// первая четверть
$settingsJoin[$key]['size'] = $rankService->fontSizeByRank(100);
} elseif ($i > $cnt and $i <= ($cnt * 2)) {
// вторая четверть
$settingsJoin[$key]['size'] = $rankService->fontSizeByRank(80);
} else {
// остальное
$settingsJoin[$key]['size'] = $rankService->fontSizeByRank(50);
}
}
}
if ($format == 'json') {
return new Response(json_encode($settingsJoin));
} elseif ($format == 'array') {
return $settingsJoin;
} elseif ($format == 'comby') {
$html = $this->render(
'@Web/Collection/setting.html.twig',
[
'locale' => $locale,
'settings' => $settingsJoin,
'flag' => $flag,
'authorLink' => $authorLink,
]
);
$html = trim(trim($html), ',');
return [
'html' => $html,
'array' => $settingsJoin,
];
} else {
return new Response($this->render(
'@Web/Collection/setting.html.twig',
[
'locale' => $locale,
'settings' => $settingsJoin,
'flag' => $flag,
'authorLink' => $authorLink,
]
));
}
}
/**
* @param $link
* @return string|string[]|null
*/
private function fixLink($link)
{
return preg_replace('#/' . App::getCurLocale() . '/#isUu', '/' . App::getCurLocale(true) . '/', $link);
}
/**
* @param array $collection
* @return string
* @throws Exception
*/
public function getSettings(array $collection): string
{
$settings = '';
if (!empty($collection['fids'])) {
$filterGroups = $this->filtersService
->loadByIds($collection['fids'], App::getCurLocale())
->buildFilterGroupsDTO();
// https://te2.remote.team/discus/BA6DD5B6-8F79-DA20-E6E6-7F983685A57D
$filterGroups
->deleteGroup('apply')
->deleteGroup('material')
->deleteGroup('samples')
->deleteGroup('using')
->deleteGroup('type');
$settings = $this->filtersService->buldFiltersToStr($filterGroups, true, false, false);
}
return $settings;
}
/**
* @param array $aData
* @param array $aSettings
* @param $nameGroup
* @param null $author
* @return array
* @throws Exception
*/
public function parseFiltersForSettings(array $aData, array $aSettings, $nameGroup, $author = null)
{
if ($nameGroup == 'Pei') {
$aSettings = $this->parsePeiForSettings($aData, $aSettings);
} else {
$aSettings = $this->parseBaseForSettings($aData, $aSettings, $nameGroup, $author);
}
return $aSettings;
}
/**
* @param array $data
* @param array $aSettings
* @return array
* @throws Exception
*/
private function parsePeiForSettings(array $data, array $aSettings)
{
$code = FilterHelper::normaliseAltName($data['pei']);
if (!ArrHelper::get($aSettings, 'Pei.' . $code)) {
$val = [
'name' => $data['pei'],
'link' => '',
'title' => App::getTranslator()->trans('catalog.options.pei'),
'noLower' => true,
'rank' => 50,
];
$aSettings['Pei'][$code] = $val;
}
return $aSettings;
}
/**
* @param array $aData
* @param array $aSettings
* @param $nameGroup
* @param null $author
* @return array
* @throws Exception
*/
private function parseBaseForSettings(array $aData, array $aSettings, $nameGroup, $author = null)
{
$aData = !ArrHelper::get($aData, "0.id") ? [$aData] : $aData;
$lcFull = App::getCurLocale(true);
$linkCatalog = $url = $this->generateUrl('app_catalog', ['_locale' => $lcFull]);
foreach ($aData as $data) {
// оптимизируем, проверяя на дубли свойств
$keyReady = $nameGroup . $data['id'];
if (in_array($keyReady, $this->readySettings)) {
continue;
}
$this->readySettings[] = $keyReady;
if ($nameGroup == 'getType') {
$nameGroup = 'getTypes';
// фикс для моноколор
} elseif ($nameGroup == 'getFacturas' and $data['id'] == '99') {
$nameGroup = 'getColors';
// фикс не верноого фильтра для типа карая Неректифицированный
} elseif ($nameGroup == 'getEdgeType' and $data['id'] == '5') {
$data['id'] = 4;
// спрятал из свойств стиль модерн по просьбе Жени https://te.remote.team/#/discus/89E08181-AE1F-67AC-0FA3-EDACFF049082/
} elseif ($nameGroup == 'getStyles' and $data['id'] == '11') {
unset($aSettings[$nameGroup]);
continue;
} elseif ($nameGroup == 'getFacturas') {
// фактуры объемная и состаренная стали объемной и состаренной поверхностями.
// https://te.remote.team/#/discus/07F31922-2ADC-9129-5616-86112BCFD072/
if ($data['id'] == '14') {
$nameGroup = 'getSurfaces';
$data['id'] = 11;
} elseif ($data['id'] == '11') {
$nameGroup = 'getSurfaces';
$data['id'] = 12;
}
}
$code = FilterHelper::normaliseAltName($data['alias']);
//App::dump($data, $aSettings, $nameGroup, "{$nameGroup}." . $code , $code);
if (!ArrHelper::get($aSettings, "{$nameGroup}.{$code}")) {
$filter = $this->filterRepository->findFilterForSettingsColletion($data['id'], $nameGroup);
if ($filter) {
$link = $this->generateUrl('app_catalog', ['_locale' => $lcFull, 'key' => $filter['url']]);
$name = $filter['name'];
// фикс для DE локали, там нужны заглавные
if (App::getCurLocale() == 'de') {
$name = ucfirst($name);
}
// Если ссылка ведет на главную каталога, значит проблема. пишем в лог
if ($link == $linkCatalog) {
$this->oLogger->critical("[bad_collection_settings_link] nameGroup: {$nameGroup}, name: {$name}, alias: {$data['alias']}, url: {$this->oRequest->getRequestUri()}");
}
if (ArrHelper::get($aData, 'hide')) {
$link = '';
}
$link = str_replace("?_locale={$lcFull}", '', $link);
$val = [
'name' => $name,
'link' => $link,
'nameGroup' => $nameGroup,
'rank' => ArrHelper::get($filter, 'rank', 50),
];
$aSettings[$nameGroup][$code] = $val;
} else {
// если фильтр не найден, тоже пишем в лог
$this->oLogger->critical("[bad_collection_settings_link] NOT FOUND nameGroup: {$nameGroup}, id: {$data['id']}, alias: {$data['alias']}, url: {$this->oRequest->getRequestUri()}");
}
}
// по старому ID стиля определяем дизайнеровский и выводим дизайнеров
if ($data['id'] == 17) {
$authors = $author ? $author : [];
foreach ($authors as $i => $authorLink) {
$authorLink = trim($authorLink);
$fAltName = FilterHelper::normaliseAltName($authorLink);
$code = StrHelper::toLower($fAltName);
if (!ArrHelper::get($aSettings, 'getStylesDesigners.' . $code)) {
// формируем заголовок для дизайнера со всякими приставками и ссылками
$key = $this->filterRepository->getKeyDesignerStyle();
$href = App::getRouter()->generate('app_catalog', ['key' => $key]);
$header = App::getTranslator()->trans('collection_header_designer');
$replace = FilterEntity::REPLACE_DESIGNE_RUSER;
$replace = $replace . '|' . StrHelper::toLower($replace);
$header = preg_replace_callback("/{$replace}/i", function ($matches) use ($href) {
$name = $matches[0];
return "<a href=\"{$href}\">#{$name}</a>";
}, $header);
if ($i != 0) {
$header = null;
}
$val = [
'header' => $header,
'name' => $authorLink,
'link' => $this->fixLink(FilterHelper::getUrl($fAltName)),
'url' => $this->fixLink(FilterHelper::getUrl($fAltName)),
'authorLink' => $authorLink,
];
$aSettings['getStylesDesigners'][$code] = $val;
}
}
}
}
//App::dump($aSettings);
return $aSettings;
}
/**
* Получаем валидную коллекцию из базы
* @param $factoryUrl
* @param $collectionUrl
* @return array
* @throws Exception
*/
public function findCollectionInDb($factoryUrl, $collectionUrl): array
{
// Получаем коллекцию по редиректу
$curRoute = App::getRequest()->get('_route');
$params = App::getRequest()->get('_route_params');
$currentUrl = App::getRequest()->getUri();
// перенаправляем те, что с _ на -,
$searchChar = '_';
$changeChar = '-';
$collUrl = str_replace($searchChar, $changeChar, $collectionUrl);
$facUrl = str_replace($searchChar, $changeChar, $factoryUrl);
if ($factoryUrl != $facUrl || $collectionUrl != $collUrl) {
$params['factoryUrl'] = $facUrl;
$params['collectionUrl'] = $collUrl;
$url = $this->generateUrl($curRoute, $params);
// если есть параметр gclid (добавляется AdWords), то оставляем его
if (strpos($currentUrl, 'gclid')) {
$gclid = substr($currentUrl, strpos($currentUrl, '?gclid'));
$url = $url . $gclid;
}
$redirect = new RedirectResponse(urldecode($url), 301);
return ['return' => $redirect];
}
$collection = $this->collectionRepository->getMainBaseCollectionLight($factoryUrl, $collectionUrl);
// проверка на сменный URL коллекции
if (!$collection) {
$redirect = $this->lastUrlService->getCollectionRedirectUrl($collectionUrl, $factoryUrl);
if ($redirect) {
$response = new RedirectResponse($redirect);
return ['return' => $response];
}
}
$collection = $this->getMainBaseCollectionHandler($collection);
// Получаем коллекцию без фильтрации по статусу, и фильтруем руками, отдавая свою заглушку вместо стандартного 404
if (
!$collection
|| $collection['status'] != BiConst::STATE_PUBLISHED
&& $collection['status'] != BiConst::STATE_DISCONTINUED
&& $collection['status'] != BiConst::STATE_WORK_CONTINUED
&& $collection['status'] != BiConst::STATE_CHECKING
&& $collection['publishDate'] == null //на основании https://te.remote.team/#/discus/7B2C1D62-1AFC-B81F-1E11-0DABFD79046D/
) {
// сказали не разделять 404 теперь
throw new NotFoundHttpException('collection not found');
}
//на основании https://te.remote.team/#/discus/7B2C1D62-1AFC-B81F-1E11-0DABFD79046D/
if ($collection['status'] > 3) {
$collection['status'] = 3;
}
$user = App::getCurUser();
if ($collection['testAccess'] && !($user && UserHelper::isEmployee($user->getEmail()))) {
throw new NotFoundHttpException('collection not found');
}
if ($collection['url'] != $collectionUrl || $collection['factory']['url'] != $factoryUrl) {
$params['factoryUrl'] = TranslitHelper::clearUrl($collection['factory']['url'], true);
$params['collectionUrl'] = TranslitHelper::clearUrl($collection['url'], true);
$url = $this->generateUrl($curRoute, $params);
// если есть параметр gclid (добавляется AdWords), то оставляем его
if (strpos($currentUrl, 'gclid')) {
$gclid = substr($currentUrl, strpos($currentUrl, '?gclid'));
$url = $url . $gclid;
}
$asJson = App::getRequest()->get('as_json', null);
if ($asJson) {
$url = $url . '?as_json=1';
}
$redirect = new RedirectResponse(urldecode($url), 301);
return ['return' => $redirect];
}
if (!empty($collection['id'])) {//count visits
$collId = $collection['id'];
$oSession = App::getSession();
$sessionCollData = $oSession->get('collectionData');
//Session has not collId >so> Collection->setViews(+1) && upd session else - continue
if (empty($sessionCollData[$collId])) {
$this->collectionRepository->increaseViewByCollectionId((int) $collId);
//upd session
$sessionCollData[$collId] = '1';
$oSession->set('collectionData', $sessionCollData);
}
}
return ['collection' => $collection];
}
/**
* Получаем строку с примененными фильтрами из FilterService, чистим ее и выдаем почищенную
* @param SearchService $oSearchService
* @return mixed|string
* @throws Exception
*/
public function getSettingsFiltersCollection(SearchService $oSearchService)
{
$oFilterService = App::getContainer()->get('app.service.filters');
$oSearchService->buildPageParams($oFilterService);
$list = $oSearchService->getTitleHtml();
preg_match_all('#<strong>(.+?)</strong>#is', $list, $arr);
$list = trim(ArrHelper::get($arr, '0.0'));
return $list;
}
/**
* Снята с производства коллекция или фабрика закрыта
* @param array $collection
* @throws Exception
*/
public function getAlertMessageIfCollectionInDiscontinuedState(array $collection): ?array
{
if ($collection['status'] == BiConst::STATE_DISCONTINUED
|| $collection['factory']['status'] == BiConst::STATE_DISCONTINUED
) {
$msg = [];
$msg['header'] = App::trans('catalog.alert.header', null, ['%name%' => $collection['name']]);
if ($collection['factory']['status'] == BiConst::STATE_PUBLISHED) {
$msg['body'] = App::trans(
'catalog.alert.msg_factory',
null,
[
'%factory%' => $collection['factory']['name'],
'%link%' => $this->generateUrl('app_catalog', [
'key' => $collection['factory']['url']
])
]
);
} else {
$msg['body'] = App::trans(
'catalog.alert.msg_catalog',
null,
[
'%catalogue%' => App::trans('catalog_simple_title'),
'%link%' => $this->generateUrl('app_catalog')
]
);
}
return $msg;
}
return null;
}
private function getMainBaseCollectionHandler($collection): ?array
{
if ($collection && count($collection) > 0) {
$locale = App::getCurLocale();
$body = !empty($collection['body']) ? $collection['body'][$locale] : null;
if ($body) {
$body = LocaleHelper::modifeLinkForLocales($body);
$body = StrHelper::replaceUmlautChar($body);
$body = TranslitNameHelper::replacePrime($body, false);
}
$collection['body'] = $body;
$collection['metaKeywords'] = $collection['metaKeywords'] ? $collection['metaKeywords'][$locale] : null;
$collection['metaDescription'] = $collection['metaDescription'] ? $collection['metaDescription'][$locale] : null;
if (BiConst::CHOICE_ADDRESS_URL) {
$furl = StrAdm::toLower($collection['factory']['url']);
$collection['factory']['url'] = $furl;
$curl = StrAdm::toLower($collection['url']);
$collection['url'] = $curl;
$collection['path'] = PathHelper::getImgWebPath() .
$furl . '/' .
$curl .
'/' . BiConst::PER_SITO . '/';
} else {
$collection['path'] = PathHelper::getImgWebPath() .
rawurlencode(TranslitHelper::clearDirName(StrAdm::toLower($collection['factory']['name']))) .
'/' . rawurlencode(str_replace(['~q~', '′'], '\'', StrAdm::toLower($collection['name']))) . '/per_sito/';
}
$actualName = empty($collection['factory']['alternateName'])
? $collection['factory']['name']
: $collection['factory']['alternateName'];
$collection['factory']['ActualName'] = str_replace(['~q~', '′'], '\'', $actualName);
$actualName = empty($collection['alternateName']) ? $collection['name'] : $collection['alternateName'];
$collection['ActualName'] = str_replace(['~q~', '′'], '\'', $actualName);
$collection['alt'] = $collection['factory']['ActualName'] . ' ' . $collection['ActualName'] . ' ';
return $collection;
}
return null;
}
}