<?php
namespace WebBundle\Controller;
use AdmBundle\Helper\Adm;
use AdmBundle\Helper\StrAdm;
use DateTime;
use Doctrine\ORM\NonUniqueResultException;
use Doctrine\ORM\NoResultException;
use Exception;
use FlexApp\Classes\CommentableEntityTypes;
use FlexApp\DTO\RequestCatalogDTO;
use FlexApp\Helper\MetaHelper;
use Import1CBundle\Helper\v3\ArticleHelper;
use Import1CBundle\Helper\v3\BiConst;
use Import1CBundle\Helper\v3\InteriorHelper;
use Memcache;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use WebBundle\Entity\Visit;
use WebBundle\Helper\App;
use WebBundle\Helper\FilterHelper;
use WebBundle\Helper\ItemHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\PathHelper;
use WebBundle\Helper\RedirectHelper;
use WebBundle\Helper\SearchLogHelper;
use WebBundle\Helper\StatsHelper;
use WebBundle\Helper\StrHelper;
use WebBundle\Helper\UrlHelper;
use WebBundle\Helper\UserHelper;
use WebBundle\Repository\ArticleRepository;
use WebBundle\Repository\BuyOrderRepository;
use WebBundle\Repository\FilterRepository;
use WebBundle\Repository\IdeaRepository;
use WebBundle\Repository\InteriorRepository;
use WebBundle\Repository\PublicationRepository;
use WebBundle\Repository\VisitRepository;
use WebBundle\Service\CollectionService;
use WebBundle\Service\CollectionSettingsService;
use WebBundle\Service\GoogleTranslateService;
use WebBundle\Service\ReviewsService;
use WebBundle\Service\SearchService;
class TileController extends ExtendedController
{
/** @required */
public ArticleRepository $articleRepository;
/** @required */
public BuyOrderRepository $buyOrderRepository;
/** @required */
public FilterRepository $filterRepository;
/** @required */
public IdeaRepository $ideaRepository;
/** @required */
public InteriorRepository $interiorRepository;
/** @required */
public PublicationRepository $publicationRepository;
/** @required */
public VisitRepository $visitRepository;
/** @required */
public CollectionService $collectionService;
/** @required */
public CollectionSettingsService $collectionSettingsService;
/** @required */
public ReviewsService $reviewsService;
/** @required */
public SearchService $searchService;
/** @required */
public GoogleTranslateService $googleTranslateService;
private int $itemsLimit = 20;
private int $interiorsLimit = 20;
/**
* @param Request $request
* @param string $factoryUrl
* @param string $collectionUrl
* @param string|null $type
* @param string|null $elementId
* @return mixed
* @throws NoResultException
* @throws NonUniqueResultException
* @throws \Doctrine\DBAL\Driver\Exception
* @throws \Doctrine\DBAL\Exception
* @throws Exception
*/
public function indexAction(
Request $request,
string $factoryUrl,
string $collectionUrl,
?string $type = null,
?string $elementId = null
) {
// проверка переноса фабрики
if ($iNeedRedirect = RedirectHelper::checkRedirect($factoryUrl, $collectionUrl, $type, $elementId)) {
return $this->redirect(
$this->generateUrl(
'app_collection',
$iNeedRedirect->getArrayForRedirect()
)
);
}
$collection = $this->collectionService->findCollectionInDb($factoryUrl, $collectionUrl);
if ($collection['return'] ?? null) {
return $collection['return'];
}
$collection = $collection['collection'];
// нет коллекции
if (!$collection) {
throw $this->createNotFoundException('Collection not found');
}
// для совместимости
$key = StrAdm::toLower($elementId);
if ($key == $collection['factory']['url']) {
return new RedirectResponse(
$this->generateUrl('app_collection', [
'factoryUrl' => $collection['factory']['url'],
'collectionUrl' => $collection['url'],
]),
301
);
}
$factoryUrl = StrAdm::toLower($factoryUrl);
$collectionUrl = StrAdm::toLower($collectionUrl);
$collection['interiors'] = $this->interiorRepository->getInteriorsForCollection($collection['id']);
//todo временно
if (!empty($collection['process'])) {
foreach ($collection['interiors'] as $k => $r) {
$collection['interiors'][$k]['file'] = preg_replace('#\.jpg#i', '.webp', $r['file']);
$collection['interiors'][$k]['a_version'] = true;
}
}
$collection['a_version'] = !empty($collection['process']);
$mainImage = PathHelper::pathGenerate('main', $collection);
// нормализуем данные страны, потом надо будет все это в нормализацию перенести
$country = $collection['factory']['country'];
$keyCountry = $this->filterRepository->getKeyByLeftMenu($country['alias']);
$collection['factory']['country'] = [
'id' => $country['id'],
'code' => StrHelper::toLower($country['code']),
'alias' => App::trans($country['alias']),
'url' => $collection['collection']['factory']['country']['url'] = App::generateUrl(
'app_catalog',
['key' => StrAdm::toLower($keyCountry)],
0
),
];
// логика по релизам коллекции
$releaseYear = !empty($collection['releaseYear']) ? $collection['releaseYear'] : null;
if ($releaseYear) {
$curYear = date("Y");
$keyYear = $curYear == $releaseYear ? 'release_year_cur' : 'release_year_' . $releaseYear;
if ($releaseYear >= '2017') {
$releaseYear = [
'year' => $collection['releaseYear'],
'text' => App::getTranslator()->trans('collection.releaseYear', ['%d%' => $releaseYear]),
'link' => FilterHelper::getUrl([$keyYear]),
];
} else {
$releaseYear = null;
}
}
if (!empty($collection['awards'])) {
$aAwards = $this->filterRepository->getAwards($collection['awards']);
if ($aAwards) {
$collection['awards'] = array_values($aAwards);
}
}
// статус использования фильтрации
$interiorsIds = false;
$itemsIds = false;
$filters = $type && $type == 'f' && $key;
if ($filters) {
//специальная проверка для псевдофильтра по артикулу
if (preg_match('#item-(.+)$#', $key, $matches)) {
$item = $this->articleRepository->getItemUrlById($matches[1]);
if (!empty($item['url'])) {
return new RedirectResponse(
$this->generateUrl('app_collection_slideshow', [
'factoryUrl' => $collection['factory']['url'],
'collectionUrl' => $collection['url'],
'type' => 'a',
'elementId' => $item['url'],
])
);
}
} else {
$keyArr = explode('&', $key);
if (count($keyArr) > 0) {
$keyNew = implode('&', $keyArr);
if ($keyNew != $key) {
$url = $this->generateUrl(
'app_collection',
[
'_locale' => App::getCurLocale(true),
'factoryUrl' => $factoryUrl,
'collectionUrl' => $collectionUrl,
'type' => $type,
'key' => $keyNew,
]
);
return new RedirectResponse($url, 301);
}
} else {
$url = $this->generateUrl(/*'app_tile'*/
'app_collection',
[
'_locale' => App::getCurLocale(true),
'factoryUrl' => $factoryUrl,
'collectionUrl' => $collectionUrl,
]
);
return new RedirectResponse($url, 301);
}
$searchFilter = [
'c_id' => [$collection['id']],
'inside' => true,
];
$reqCatDTO = new RequestCatalogDTO($request, $key, null);
$oSearchService = $this->searchService->setFilter($reqCatDTO, $searchFilter);
$titleHtml = strip_tags($oSearchService->getTitleHtml());
$titleHtml = preg_replace('/ edit/ui', '', $titleHtml);
// перенаправляем на верную страницу каталога
if ($oSearchService->isRedirect()) {
return $oSearchService->getRedirect();
}
$data = $oSearchService->getSearchData();
$keyString = serialize($data);
$memcache_key = 'sphinx' . md5($keyString);
$searchTrue_cache = App::getMemcache()->get($memcache_key);
if ($searchTrue_cache !== false) {
$searchTrue = $searchTrue_cache;
} else {
$searchTrue = App::searchSphinx($data, 0, true);
App::getMemcache()->set($memcache_key, $searchTrue);
}
// собираем id подходящих артикулов и интерьеров
if (!empty($searchTrue) && $searchTrue != false) {
$interiorsIds = !empty($searchTrue[0]['interiors'])
? array_values(array_unique(array_column($searchTrue[0]['interiors'], 'i_id')))
: false;
$itemsIds = !empty($searchTrue[0]['articles'])
? array_values(array_unique(array_column($searchTrue[0]['articles'], 'a_id')))
: false;
}
$filters = [
'list' => $this->collectionService->getSettingsFiltersCollection($oSearchService),
'linkToCataloge' => $this->generateUrl('app_catalog', ['key' => $key]),
];
$isInteriorsSuitable = false;
$sortInteriorsIds=[];
foreach ($collection['interiors'] as $i => $interior) {
if ($interiorsIds && in_array($interior['id'], $interiorsIds)) {
// App::debug(array_search($interior['id'], $interiorsIds));
$collection['interiorsSuitable'][array_search($interior['id'], $interiorsIds)] = $interior;
$sortInteriorsIds[array_search($interior['id'], $interiorsIds)] = $interior['id'];
unset($collection['interiors'][$i]);
$isInteriorsSuitable = true;
}
}
if ($isInteriorsSuitable) {
ksort($collection['interiorsSuitable']);
$collection['interiorsSuitable']= array_values($collection['interiorsSuitable']);
$collection['interiors'] = array_values($collection['interiors']);
$interiorsIds = $sortInteriorsIds;
}
// App::debugExit($collection['interiorsSuitable']);
}
} else {
$this->oSession()->set('searchData', []);
$collection['interiorsSuitable'] = [];
}
$imagePreload = null;
$imagePreload2 = null;
if (!empty($collection['interiorsSuitable'])){
foreach ($collection['interiorsSuitable'] as $i => $interior) {
$itemInterior = InteriorHelper::getInteriorDetails($interior, $collection, $i, $key);
$collection['interiorsSuitable'][$i] = $itemInterior;
if (!$imagePreload && !empty($itemInterior['pathImg'])) {
$imagePreload = $itemInterior['pathImg'];
}
if ($imagePreload && !$imagePreload2 && !empty($itemInterior['pathImg'])) {
$imagePreload2 = $itemInterior['pathImg'];
}
}
}
foreach ($collection['interiors'] as $i => $interior) {
$itemInterior = InteriorHelper::getInteriorDetails($interior, $collection, $i, $key);
$collection['interiors'][$i] = $itemInterior;
if (!$imagePreload && !empty($itemInterior['pathImg'])) {
$imagePreload = $itemInterior['pathImg'];
}
if ($imagePreload && !$imagePreload2 && !empty($itemInterior['pathImg'])) {
$imagePreload2 = $itemInterior['pathImg'];
}
}
$reviews = $this->reviewsService->getReviewsByCollectionId((int) $collection['id']);
//App::debugExit($collection['interiors'],$collection['interiorsSuitable']);
$preData = $reviews;
unset($preData['percent']);
unset($preData['list']);
unset($preData['stars']);
// получаем все количество интерьеров и артикулов коллекции
$interiorsCount = $this->interiorRepository->countInteriorsColl($collection['id']);
$interiorsSuitableCount = $interiorsIds ? $this->interiorRepository->countInteriorsColl(
$collection['id'],
$interiorsIds
) : 0;
$favorites = $this->ideaRepository->getInteriorsIdeasByToken(UserHelper::getInstance()->getToken());
$isFreezed = in_array($collection['status'], [BiConst::STATE_DISCONTINUED, BiConst::STATE_PROCESSING])
|| in_array($collection['factory']['status'], [BiConst::STATE_DISCONTINUED, BiConst::STATE_PROCESSING]);
// вызывало такую ошибку https://te.remote.team/#/discus/C3E213E9-F69E-543B-6D32-4F5724BC1FA5/
// if ($itemsIds) {
// $itemsCount = count($itemsIds);
//// $itemsIdArray = $itemsIds;
// } else {
// $itemsIdArray = $repoArticle->getArticlesIdColl($collection['id']);
// $itemsCount = $repoArticle->countArticlesColl($collection['id'], false, $isFreezed);
// }
$itemsIdArray = $this->articleRepository->getArticlesIdColl($collection['id']);
$itemsCount = $this->articleRepository->countArticlesColl($collection['id'], false, $isFreezed);
// отключили артикулы без изображений https://te.remote.team/#/discus/89045B58-C74C-0E9E-762B-13C59633635A/
//$itemsNoImgCount = $repoArticle->countArticlesColl($collection['id'], false, $isFreezed, true);
$userCurrency = LocaleHelper::getCur();
$currency = LocaleHelper::getCurrency();
// получение минимальной цены арта
$minPrice = $this->articleRepository->getArticleMinPriceByCollectionId($collection['id']);
$settings = '';
$settingsReact = [];
if (!empty($collection['fids'])) {
$settings = $this->collectionSettingsService->getFiltersHtml($collection['fids']);
$settingsReact = $this->collectionSettingsService->getFilters($collection['fids'], true);
}
$publishDate = $collection['publishDate'];
if ($publishDate instanceof DateTime) {
$publishDate = $publishDate->format('d.m.Y');
}
$msg = $this->collectionService->getAlertMessageIfCollectionInDiscontinuedState($collection);
$collection = array_merge($collection, [
'ratingHelp' => App::trans(
$collection['rating'] == 1
? 'collection_ideas_summ'
: 'collection_ideas_summ_many',
null,
['%count%' => $collection['rating']]
),
'targetItem' => false,
'settings' => $settings,
'settingsReact' => $settingsReact,
'reviews' => $reviews,
'preData' => $preData,
'starsOf' => App::trans('product_review_by', null, ['%d%' => $reviews['percent']['d']]),
'releaseYear' => $releaseYear,
'publishDate' => $publishDate,
'linkEdit' => Adm::linkEdit('adm.collection.edit', $collection['id']),
'linkEditBi' => Adm::linkEdit('bi_collection_show_check', $collection['id']),
'isFreezed' => $isFreezed,
'closed' => ($collection['status'] == BiConst::STATE_DISCONTINUED
? App::trans('catalog_out_of_production')
: ($collection['status'] == BiConst::STATE_PROCESSING
? App::trans('collection_unavailable')
: ''
)),
'closedHelp' => $collection['status'] == BiConst::STATE_PROCESSING
? App::trans('collection_unavailable_manufacture_desc')
: '',
'filters' => $filters,
'addIdeaUrl' => App::generateUrl('app_ideas_list', ['id' => '']),
'interiorsUrl' => App::generateUrl('app_tile_interiors', ['id' => $collection['id']]),
'itemSettingsUrl' => App::generateUrl('app_article_settings', ['id' => 0]),
'preDataCollectionReviewsUrl' => App::generateUrl('pre_data_collection_reviews', ['id' => $collection['id']]),
'collectionReviewsUrl' => App::generateUrl('collection_reviews', ['id' => $collection['id']]),
'interiorsCount' => $interiorsCount,
'interiorsIds' => $interiorsIds,
'interiorsSuitableCount' => $interiorsSuitableCount,
'interiorsMore' => false,
'interiorsSuitableMore' => false,
'favorites' => $favorites,
'itemsUrl' => App::generateUrl('app_tile_items', ['id' => $collection['id']]),
'itemsCount' => $itemsCount/* + $itemsNoImgCount*/,
'itemsIdArray' => $itemsIdArray,
'itemsSuitableCount' => $itemsIds ? count($itemsIds) : 0,
'itemsMore' => true,
'itemsSuitableMore' => true,
'itemsNoImgMore' => false,//$repoArticle->countArticlesColl($collection['id'], false) > 0,
'items' => [],
'itemsSuitable' => [],
'itemsNoImg' => [],
'itemsNoImgCount' => 0,//(int)$itemsNoImgCount,
'itemsIds' => $itemsIds,
'alsoViewed' => null,
'alsoViewedUrl' => App::generateUrl('app_article_info', ['collectionId' => $collection['id']]),
'commentsCounts' => $this->collectionService->getCommentsCountData($collection['unid'] ?? ''),
'commentsBlockUrl' => App::generateUrl(
'app_comment_block',
[
'entity' => $collection['id'],
'type' => CommentableEntityTypes::COLLECTION,
'unid' => $collection['unid'] ?? null,
]
),
'collection_reviews' => '',
'userCountry' => App::getCurCountry(),
'userLocale' => App::getCurLocale(),
'userCurrency' => $userCurrency,
'currency' => $currency,
'isWithoutVATPrice' => LocaleHelper::isWithoutVATPrice(10) !== false,
'vatPercent' => LocaleHelper::includeVATAlways(),
'measureGb' => LocaleHelper::measureGb(),
'minPrice' => $minPrice,
'priceSort' => LocaleHelper::getPrMin($collection),
'priceSortCur' => LocaleHelper::getCur(),
'priceSortMea' => LocaleHelper::getUserMeasure(),
'notRegular' => App::trans(
'collection.notRegular',
null,
[
'%suspended_brand%' => $collection['factory']['name'],
]
),
'trans' => $this->trans(),
'msg' => $msg,
]);
//App::debugExit($collection);
// получаем мета по данной странице
$metaManager = MetaHelper::getManager($collection);
$title = $metaManager->getTitle();
if (!empty($titleHtml)) {
$titleHtml = trim(preg_replace('/(^.+\.)/', '', $titleHtml), "\n");
$title = preg_replace('/\. .+/', '', $title) . '. ' . $titleHtml;
}
// нормализуем заголовок
$collHeader = $this->get('translator')->trans(
$collection['header'],
[
'%collection%' => preg_replace('#\\(.*\\)#isUu', '', $collection['ActualName']),
'%factory%' => $collection['factory']['ActualName'],
'%factoryUrl%' => App::generateUrl(
'app_catalog',
[
'key' => $factoryUrl,
],
UrlGeneratorInterface::ABSOLUTE_URL
),
]
);
// защита от "дурака" когда в переводе добавляют в начало ссылки /;
$collection['header'] = str_replace('href="/', 'href="', $collHeader);
// логика под вывод ссылки на затирки и смеси
if ($glueUrl = $collection['glueUrl']) {
$glue['url'] = $this->generateUrl('app_collection', [
'factoryUrl' => $factoryUrl,
'collectionUrl' => $glueUrl,
]);
$glue['text'] = App::getTranslator()->trans('adhesives_grouts_glass_link');
$collection['glue'] = $glue;
}
// сохраняем запись в историю обязательно после нормализации заголовка
$this->addHistory($collection);
StatsHelper::addHitsColl($collection['id']);
SearchLogHelper::save(['url' => App::getRequest()->getUri(), 'title' => $title]);
/* Временно отключена отправка событий */
// // отправка события в амазон
// $token = UserHelper::getInstance()->getToken();
// /** @var UserRepository $userRepo */
// $userRepo = App::getRepository(User::class);
// /** @var User $user */
// $user = $userRepo->getUserByToken($token);
// $userId = $user ? $user->getId() : 0;
// $amazonPersonalizeService = $this->getAmazonPersonalizeService();
// /*$eventSent = нигде не используется*/
// $amazonPersonalizeService->putEvent($userId, (int)$collection['id'], 'click', App::getSession()->getId());
// Специальная ссылка на блог
$blog = $this->publicationRepository->find(2232);
$collection['fastDeliverySamplesUrl'] = UrlHelper::genUrlBlogSingle($blog);
//App::debugExit([
// 'imagePreload' => $imagePreload,
// 'imagePreload2' => $imagePreload2,
// 'mainImage' => $mainImage,
// 'type' => $type,
// 'meta' => [
// 'title' => $title,
// 'description' => $metaManager->getDescription(),
// 'keywords' => $metaManager->getKeywords(),
// 'specs' => $settingsReact ? FilterHelper::filterText($settingsReact) : null,
// ],
// 'initialState' => ['collection' => $collection],
// 'ldJson' => $collection['status'] == BiConst::STATE_PUBLISHED && LocaleHelper::getPrMin($collection) > 0,
//]);
return $this->renderReact('@Web/Tile/index.html.twig', [
'imagePreload' => $imagePreload,
'imagePreload2' => $imagePreload2,
'mainImage' => $mainImage,
'type' => $type,
'meta' => [
'title' => $title,
'description' => $metaManager->getDescription(),
'keywords' => $metaManager->getKeywords(),
'specs' => $settingsReact ? FilterHelper::filterText($settingsReact) : null,
],
'initialState' => ['collection' => $collection],
'ldJson' => $collection['status'] == BiConst::STATE_PUBLISHED && LocaleHelper::getPrMin($collection) > 0,
]);
/**
* для реакта добавлены переменные
*
* interior.pathImg
* [pathImg] => https://img.tile.expert/img_lb/bisazza/campana/per_sito/ambienti/z_bisazza_campana_2_1.jpg
* interior.x
* [x] => 314
* interior.y
* [y] => 400
* interior.imgAlt
* [imgAlt] => Bisazza-campana-1, handmade,designer Style, Bisazza-campana-2, handmade,designer,handmade,designer Style
* interior.slideShowInteriorLink
* [slideShowInteriorLink] => /en/slideshow-images/3246088/i/174155/link
*/
}
/**
* Возвращает порцию артикулов коллекции
* @param int $id
* @param ?int $page
* @return JsonResponse
* @throws Exception
* @throws \Doctrine\DBAL\Driver\Exception
*/
public function itemsAction(int $id, ?int $page = 1): JsonResponse
{
$limit = $this->itemsLimit;
$repoArticle = $this->articleRepository;
$ordersItems = $this->buyOrderRepository->getInfoBuyOrderArticle(UserHelper::getInstance()->getToken(), false, $id);
//загрузка до страницы
if (App::getRequest()->get('loadAll')) {
$limit = $limit * $page;
$page = 1;
}
$params = [
'collection' => $id,
'offset' => $limit * $page - $limit,
'limit' => $limit,
];
// показывать так же снятые артикулы
if (App::getRequest()->get('isFreezed', false) == 'true') {
$params['isFreezed'] = 1;
}
$suitable = App::getRequest()->get('suitable', false) == 'true';
$keyName = 'items' . ($suitable ? 'Suitable' : '');
if (App::getRequest()->get('itemsIds', false) != 'false') {
$params[$suitable ? 'items' : 'notItems'] = explode(',', App::getRequest()->get('itemsIds'));
}
$items = $repoArticle->getArticleNativeOpt($params, true);
// нужно проставить индексы, чтобы react воспринял как массив
$res = [];
$i = $params['offset'];
foreach ($items as $item) {
if ($texture = $item['details']['variantImage']['texture'] ?? null) {
$item['variantImage']['texture'] = ItemHelper::addMainPic(
$texture,
StrHelper::toLower($item['details']['file'])
);
}
if ($picture = $item['details']['variantImage']['picture'] ?? null) {
$item['variantImage']['picture'] = ItemHelper::addMainPic(
$picture,
StrHelper::toLower($item['details']['file'])
);
}
$item['shape'] = empty($item['shape']) ? ['id' => null, 'alias' => null] : $item['shape'];
$item['mea'] = App::trans(LocaleHelper::getMeasure($item));
$item['amount'] = LocaleHelper::getAmount($item);
$item['orders'] = !empty($ordersItems[$item['id']]) ? $ordersItems[$item['id']] : false;
$item['suitable'] = $suitable;
$options = ArticleHelper::getTileArticleAddOptions($item);
$res[$i] = $options;
$i++;
}
if (count($items) == $limit) {
$params['limit'] = 1;
$items = $repoArticle->getArticleNativeOpt($params, true);
$more = count($items) > 0;
} else {
$more = false;
}
return new JsonResponse(['items' => $res, 'more' => $more, 'keyName' => $keyName, 'nextPage' => $page + 1]);
}
/**
* Возвращает порцию интерьеров коллекции
* @param int $id
* @param ?int $page
* @return JsonResponse
* @throws Exception
* @internal param string $sort
*/
public function interiorsAction(int $id, ?int $page = 1): JsonResponse
{
$limit = $this->interiorsLimit;
$offset = $limit * $page - $limit;
$suitable = App::getRequest()->get('suitable', false) == 'true';
$keyName = 'interiors' . ($suitable ? 'Suitable' : '');
if (App::getRequest()->get('interiorsIds') && App::getRequest()->get('interiorsIds') != 'false') {
$params[$suitable ? 'ids' : 'notIds'] = explode(',', App::getRequest()->get('interiorsIds'));
} else {
$params = [];
}
$interiors = $this->interiorRepository->getInteriors($id, $params);
$favorites = $this->ideaRepository->getInteriorsIdeasByToken(UserHelper::getInstance()->getToken());
// нужно проставить индексы чтобы react воспринял как массив
$res = [];
$i = $offset;
foreach ($interiors as $interior) {
$alt[] = $interior['name'];
foreach ($interior['styles'] as $k => $style) {
$interiors[$i]['styles'][$k]['alias'] = $alt[] = App::trans($style['alias']);
}
foreach ($interior['textures'] as $k => $texture) {
$interiors[$i]['textures'][$k]['alias'] = $alt[] = App::trans($texture['alias']);
}
$interiors[$i]['alt'] = join(', ', $alt);
$interior['favorite'] = !empty($favorites[$interior['id']]);
$interior['suitable'] = $suitable;
$res[$i] = $interior;
$i++;
}
return new JsonResponse(['interiors' => $res, 'more' => false, 'keyName' => $keyName]);
}
/**
* Добавляет запись в историю просмотров
*
* @param $collection
* @throws NoResultException
* @throws NonUniqueResultException
* @throws Exception
*/
private function addHistory($collection)
{
$headerVisited = implode(' ', [
$collection['ActualName'],
$this->get('translator')->trans('collection_by'),
$collection['factory']['ActualName'],
]);
$icon = $collection['path'] . 'main.jpg';
$factoryUrl = StrAdm::toLower($collection['factory']['url']);
$collectionUrl = StrAdm::toLower($collection['url']);
// специально чтобы ссылки с выбранными фильтрами рассматривались как стандартная ссылка на коллекцию
$url = $this->generateUrl(
'app_collection',
[
'_locale' => App::getCurLocale(true),
'factoryUrl' => $factoryUrl,
'collectionUrl' => $collectionUrl,
],
0
);
$this->visitRepository->setVisit(
$headerVisited,
$icon,
$url,
null,
Visit::TYPE_VISIT['COLLECTION'],
$collection['id']
);
}
/**
* Переводы для страницы коллекции
* @return array
* @throws \Doctrine\DBAL\Driver\Exception
* @throws \Doctrine\DBAL\Exception
* @throws Exception
*/
private function trans(): array
{
$translator = App::getTranslator();
return [
'loc' => App::getCurLocale(true),
'lang' => App::getCurLocale(),
'settings' => $translator->trans('collection_marks'),
'added' => $translator->trans('collection_added'),
'star' => $translator->trans('reviews.stars.one'),
'stars' => $translator->trans('reviews.stars.many'),
'reviewShowAll' => $translator->trans('product_review_show_all'),
'catalogMoreDown' => $translator->trans('catalog_more_down'),
'catalogMoreUp' => $translator->trans('catalog_more_up'),
'descCollectionHeader' => $translator->trans('descCollectionHeader'),
'commentAddQuestion' => $translator->trans('comment_add_question'),
'collectionVideos' => $translator->trans('collection.videos'),
'collectionBack' => $translator->trans('collection_back'),
'productReview' => [
$translator->trans('product_review'),
$translator->trans('product_review_'),
$translator->trans('product_reviews'),
],
'comments' => $translator->trans('blog_comments'),
'of' => $translator->trans('of'),
'more' => $translator->trans('show_more'),
'effect' => $translator->trans('left_menu_effect'),
'style' => $translator->trans('left_menu_style'),
'reviews' => [
'heading' => $translator->trans('collection_customer_reviews'),
'validUser' => $translator->trans('product_validUser'),
'reply' => $translator->trans('reply_comment'),
'edit' => $translator->trans('edit'),
'save' => $translator->trans('save'),
'cancel' => $translator->trans('cancel'),
],
'item' => [
'collection' => $translator->trans('collection_name'),
'factory' => $translator->trans('catalog_factory'),
'characteristics' => $translator->trans('article_characteristics'),
'tile' => $translator->trans('footer_tile'),
'item' => $translator->trans('collection_article'),
'header' => $translator->trans('collection_articles_d'),
'formats' => $translator->trans('article_item_formats'),
'cm' => $translator->trans('left_menu_cm'),
'inch' => '″',
'diameter' => $translator->trans('article_item_diameter'),
'pcs' => $translator->trans('measure_unit'),
'pcsPlural' => $translator->trans('measure_units'),
'set' => $translator->trans('measure_set'),
'sets' => $translator->trans('measure_sets'),
'price' => $translator->trans('catalog_price'),
'vat' => [
'label' => $translator->trans('vat.label'),
'included' => $translator->trans('vat.included'),
'excluded' => $translator->trans('vat.excluded'),
],
'info' => $translator->trans('article_item_more_info'),
'infoLess' => $translator->trans('article_item_less_info'),
'order' => [
'help' => $translator->trans('buyOrder.help'),
'ceilToPallet' => $translator->trans('collection_ceil_to_pallet'),
'atentionPallet' => $translator->trans('collection_atention_pallet'),
'popupAutoChangeCountArts' => $translator->trans('popup_auto_change_count_arts'),
],
'up' => $translator->trans('article.price.up'),
'down' => $translator->trans('article.price.down'),
'readMore' => $translator->trans('read_more'),
'titleAddedArticle' => $translator->trans('buyOrder.titleAddedArticle'),
'addIntoOrder' => $translator->trans('buy_order.add_into_order'),
'headerOrderAdd' => $translator->trans('header_order_add'),
'draft' => $translator->trans('order.status.draft'),
'typeMain' => $translator->trans('article.type.main'),
'typeSample' => $translator->trans('article.type.sample'),
'sampleText' => $translator->trans('article.type.sampleText'),
'typeCompare' => $translator->trans('article.type.compare'),
'compareText' => $translator->trans('article.type.compareText'),
'type3d' => $translator->trans('article.type.3d'),
'text3d' => $translator->trans('article.type.3dText'),
'articleOrderOver' => $translator->trans('article.order.over'),
'articleOrderMultiplies' => $translator->trans('article.order.multiplies'),
'articlePricePerPallet' => $translator->trans('article.price.perPallet'),
'articlePriceNoLessPallet' => $translator->trans('article.price.noLessPallet'),
'articlePricePalleteFrom' => $translator->trans('article.pricePallete.from'),
'articlePriceFrom' => $translator->trans('article.price.from'),
'articlePricePalleteUnder' => $translator->trans('article.pricePallete.under'),
'articlePriceFromTo' => $translator->trans('article.price.from_to'),
'articlePriceFromLine' => $translator->trans('catalog_price_from'),
'articlePriceToLine' => $translator->trans('dimensions_to'),
'boxArticleSingle' => $translator->trans('box_article_single'),
'boxArticlePlural' => $translator->trans('box_article_plural'),
'articleNoImgTitle' => $translator->trans('article.no_img'),
'collectionAddOrder' => $translator->trans('collection_add_order'),
'discountinued' => $translator->trans('article.discountinued'),
'tempNoUKShippingMsg' => $translator->trans('msg.uk'),
'tempUnavailable' => $translator->trans('article.temp_unavailable'),
],
'sample' => [
'folder' => $translator->trans('sample.folder.text'),
'original' => $translator->trans('sample.original.text'),
'piece' => $translator->trans('sample.piece.text'),
'title' => $translator->trans('samplePopup.title'),
'noMoreShow' => $translator->trans('samplePopup.noMoreShow'),
'withDecl' => $translator->trans('article.type.sampleWithDecl'),
'alreadyAdded' => $translator->trans('sample_already_added.header'),
],
'interior' => [
'header' => $translator->trans('collection_interiors_d'),
'msg' => $translator->trans('collection.interior.msg'),
'ideaHelp' => [
'added' => $translator->trans('idea_msg_added'),
'normal' => $translator->trans('idea_msg_normal'),
'normalMany' => $translator->trans('idea_msg_normal_many'),
'normalZero' => $translator->trans('idea_msg_normal_zero'),
'collectionIdeasShort' => $translator->trans('collection_ideas_short'),
],
],
'sampleBlog' => $this->publicationRepository->getUrlBlogExpressSamples(),
'unavailableFreezedDescArticle' => $translator->trans('collection_unavailable_freezed_desc_article'),
'collectionTempUnavailable' => $translator->trans('collection.temp_unavailable'),
'notAvailableInRuCountry' => $translator->trans('product_not_available_in_ru'),
'searchResult' => $translator->trans('search_result'),
'suitableElements' => $translator->trans('collection_suitable_elements'),
'otherElements' => $translator->trans('collection_other_elements'),
'anonymously' => $translator->trans('anonymously'),
];
}
public function translateArticleAction(int $elementId, string $lang): JsonResponse
{
return new JsonResponse([
'result' => $this->googleTranslateService->translateCommentForArticle($elementId, $lang),
]);
}
}