<?php
declare(strict_types=1);
namespace WebBundle\Service;
use Exception;
use FlexApp\DTO\RequestCatalogDTO;
use FlexApp\Service\Meta\MetaManager;
use Import1CBundle\Helper\v3\ArticleHelper;
use Import1CBundle\Helper\v3\InteriorHelper;
use Import1CBundle\Helper\v3\TranslitNameHelper;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Contracts\Translation\TranslatorInterface;
use WebBundle\Enum\ArticleStateEnum;
use WebBundle\Exception\ArticleNotAvailableNowException;
use WebBundle\Helper\App;
use WebBundle\Helper\ArticleSettingsHelper;
use WebBundle\Helper\ConversionHelper;
use WebBundle\Helper\ItemHelper;
use WebBundle\Helper\LocaleHelper;
use WebBundle\Helper\PathHelper;
use WebBundle\Helper\StrHelper;
use WebBundle\Repository\ArticleRepository;
use WebBundle\Repository\BuyOrderRepository;
use WebBundle\Repository\FilterRepository;
use WebBundle\Repository\IdeaRepository;
use WebBundle\Repository\InteriorRepository;
use WebBundle\Repository\ListCountryRepository;
class SliderService
{
/** @required */
public ArticleRepository $articleRepository;
/** @required */
public InteriorRepository $interiorRepository;
/** @required */
public IdeaRepository $ideaRepository;
/** @required */
public BuyOrderRepository $buyOrderRepository;
/** @required */
public FilterRepository $filterRepository;
/** @required */
public ListCountryRepository $listCountryRepository;
/** @required */
public SearchService $searchService;
/** @required */
public SampleService $sampleService;
private TranslatorInterface $translator;
public function __construct(TranslatorInterface $translator)
{
$this->translator = $translator;
}
/**
* @param Request $request
* @param string $token
* @param string $type
* @param array $collection
* @param string|null $elementId
* @param string|null $load
* @return array
* @throws Exception|\Doctrine\DBAL\Driver\Exception|ArticleNotAvailableNowException
*/
public function getData(
Request $request,
string $token,
string $type,
array $collection,
?string $elementId = null,
?string $load = 'all'
): array {
if ($type == 'a') {
$elementsCount = $this->articleRepository->countArticlesColl(
$collection['id'],
$request->get('all', false)
);
$params = [
'collection' => $collection['id'],
'offset' => 0,
'limit' => 200000,
];
$elements = $this->articleRepository->getArticleNativeOpt($params, true);
$elements = $this->prepareDiscountAmountForEachArticle($elements);
$elementIdes = array_column($elements, 'id');
$elementUrls = array_column($elements, 'url');
$elements = array_combine($elementIdes, $elements);
if (in_array($elementId, $elementUrls)) {
if (
$redirectArticle = $this->articleRepository->findOneBy([
'url' => $elementId,
'collection' => $collection['id'],
])
) {
$elementId = $redirectArticle->getId();
}
} elseif (array_key_exists($elementId, $elements)) {
// если ключ элемента цифровой - запросим редирект
// https://tile.expert/ru-it/tile/del-conca/hcl-climb/a/288881155
return [
'redirect' => App::generateUrl(
'app_collection_slideshow',
[
'factoryUrl' => $collection['factory']['url'],
'collectionUrl' => $collection['url'],
'type' => $type,
'elementId' => $elements[$elementId]['url'],
]
),
];
} else {
// артикула нет!
throw new NotFoundHttpException('The element is not found');
}
$this->checkAvailableArticle($elements[$elementId]);
$res = $this->getIdes($elementIdes, $elementId, $load);
$elements = $this->articleRepository->getArticleNativeOpt(
[
'collection' => $collection['id'],
'status' => $collection['status'],
'interior' => true,
'items' => $res['ides'],
'isFreezed' => false,
],
);
$elements = $this->prepareDiscountAmountForEachArticle($elements);
} else {
$elementsCount = $this->interiorRepository->countInteriorsColl($collection['id']);
$res = $this->interiorRepository->interiorId($elementId, $collection['id']);
if (!$res) {
$url = $this->interiorRepository->interiorUrlByName($elementId, $collection['id']);
if ($url) {
return [
'redirect' => App::generateUrl(
'app_collection_slideshow',
[
'factoryUrl' => $collection['factory']['url'],
'collectionUrl' => $collection['url'],
'type' => 'i',
'elementId' => $url,
]
),
];
}
}
$elementId = $res;
$filter = $request->get('filter');
if ($filter) {
$searchFilter = [
'c_id' => [$collection['id']],
'inside' => true,
];
$reqCatDTO = new RequestCatalogDTO($request, $filter, null);
$oSearchService = $this->searchService;
$oSearchService->setFilter($reqCatDTO, $searchFilter);
$data = $oSearchService->getSearchData();
$keyString = serialize($data);
$key = 'sphinx' . md5($keyString);
$searchTrue_cache = App::getMemcache()->get($key);
if ($searchTrue_cache !== false) {
$searchTrue = $searchTrue_cache;
} else {
$searchTrue = App::searchSphinx($data, 0, true);
App::getMemcache()->set($key, $searchTrue);
}
$elementIdesAll_ = $this->interiorRepository->getInteriorsForSlider(
$collection['id'],
['onlyId' => true]
);
if (!empty($searchTrue[0]['interiors'])) {
$elementIdesFind = array_column($searchTrue[0]['interiors'], 'i_id');
if (in_array($elementId, $elementIdesFind)) {
$elementIdes = array_values($elementIdesFind);
} else {
$elementIdes = array_column($elementIdesAll_, 'id');
$elementIdes = array_values(array_diff($elementIdes, $elementIdesFind));
}
$elementsCount = count($elementIdes);
} else {
$elementIdes = array_column($elementIdesAll_, 'id');
}
$res = $this->getIdes($elementIdes, $elementId, $load);
$elements = $this->interiorRepository->getInteriorsForSlider(
$collection['id'],
['ids' => $res['ides']]
);
foreach ($elements as &$element) {
$element = InteriorHelper::getInteriorDetails($element, $element['collection'], null, $filter);
}
} else {
$elementIdes = $this->interiorRepository->getInteriorsForSlider($collection['id'], ['onlyId' => true]);
$res = $this->getIdes(array_column($elementIdes, 'id'), $elementId, $load);
$elements = $this->interiorRepository->getInteriorsForSlider(
$collection['id'],
['ids' => $res['ides']]
);
foreach ($elements as &$element) {
$element = InteriorHelper::getInteriorDetails($element, $element['collection']);
}
}
}
$favorites = $this->ideaRepository->getInteriorsIdeasByToken($token);
$nameF = $collection['factory']['name'];
$pos = isset($collection['factory']['name']) ? strpos($collection['factory']['name'], '′') : false;
if ($pos !== false) {
$name = TranslitNameHelper::replacePrime($collection['factory']['name'], false);
$nameF = $name;
}
$titleData = [
'c_id' => $collection['id'],
'c_name' => $collection['name'],
'c_satus' => $collection['status'],
'f_id' => $collection['factory']['id'],
'f_name' => $nameF,
'f_satus2' => $collection['factory']['status'],
'code' => $collection['factory']['country']['code'],
'type' => $type,
'elsCount' => $elementsCount,
];
$buyOrderArticle = $this->buyOrderRepository->getInfoBuyOrderArticle($token);
$samplesArray = [];
if ($request->get('sample')) {
$samplesArray = $this->sampleService
->getSamplesData(
array_column($elements, 'code'),
(string)App::getCurCountryId(),
false,
LocaleHelper::getCur(),
LocaleHelper::getUserMeasure()
);
}
$newElements = [];
$ordersItems = $this->buyOrderRepository->getInfoBuyOrderArticle($token);
foreach ($elements as $row) {
$row = $this->unsetInactiveArticleInInteriorOrCollection($row);
$newElements[$row['id']] = $newElements[$row['id']] ?? $row;
$newElements[$row['id']]['name'] = html_entity_decode($row['name']);
$newElements[$row['id']]['alternateName'] = empty($row['alternateName']) ? null : html_entity_decode(
$row['alternateName']
);
$newElements[$row['id']]['numberElement'] = $res['numberElement'][$row ['id']];
$titleData['id'] = $row['id'];
$titleData['elNum'] = $res['numberElement'][$row['id']];
$newElements[$row['id']]['collection']['priceSort'] = LocaleHelper::getPrMin($row['collection']);
$newElements[$row['id']]['collection']['priceSortCur'] = LocaleHelper::getCurrency();
$newElements[$row['id']]['collection']['priceSortMea'] = LocaleHelper::getUserMeasure();
$this->addInfoAboutAvailableInCountryOfFactory($row['collection'], $newElements[$row['id']]);
$furl = $row['collection']['factory']['url'] ?? null;
$curl = $row['collection']['url'] ?? null;
if ($type == 'i') {
if (empty($row['file'])) {
$row['file'] = StrHelper::toLower($row['name']) . '.jpg';
} else {
$row['file'] = StrHelper::toLower($row['file']);
}
//todo временно
if (!empty($newElements[$row['id']]['collection']['process'])) {
$row['file'] = preg_replace('#\.jpg#i', '.webp', $row['file']);
$isWebp = $newElements[$row['id']]['collection']['a_version'] = true;
} else {
$isWebp = $newElements[$row['id']]['collection']['a_version'] = false;
}
foreach ($row['articles'] as $n => $article) {
if (empty($article['collection'])) {
unset($newElements[$row['id']]['articles'][$n]);
continue;
}
$afurl = $article['collection']['factory']['url'] ?? null;
$acurl = $article['collection']['url'] ?? null;
$article['name'] = html_entity_decode($article['name']);
$article['alternateName'] = empty($article['alternateName']) ? null : html_entity_decode(
$article['alternateName']
);
$article['addUrl'] = App::generateUrl(
'app_buy_orders_list',
[
'articleId' => $article['id'],
]
);
$article['sampleUrl'] = App::generateUrl('app_order_sample', ['code' => $article['code']]);
$article['collectionUrl'] = App::generateUrl(
'app_collection',
[
'factoryUrl' => $afurl,
'collectionUrl' => $acurl,
]
);
$article['factoryUrl'] = App::generateUrl(
'app_catalog',
[
'key' => $afurl,
]
);
$article['prc'] = LocaleHelper::getPrice($article);
$article['mea'] = App::trans(LocaleHelper::getMeasure($article));
// рассчитываем размер в inch-ах
$article['sizeGbX'] = ConversionHelper::convertInch((float)$article['sizeX'], ConversionHelper::CM);
$article['sizeGbY'] = ConversionHelper::convertInch((float)$article['sizeY'], ConversionHelper::CM);
$article['sizeGbZ'] = ConversionHelper::convertInch((float)$article['sizeZ'], ConversionHelper::CM);
$article['amount'] = LocaleHelper::getAmount($article);
$article['orders'] = !empty($ordersItems[$article['id']]) ? $ordersItems[$article['id']] : false;
$article['ssLink'] = App::generateUrl(
'app_collection_slideshow',
[
'factoryUrl' => $afurl,
'collectionUrl' => $acurl,
'type' => 'a',
'elementId' => $article['url'],
]
);
$article['imageSettingIcon'] = ArticleHelper::getPathArticleImageSettings($article);
$article['shape'] = [
'id' => $article['shape']['id'],
'alias' => App::trans($article['shape']['alias']),
];
if ($isWebp) {
$articleFileNameWebp = preg_replace('#\.jpg#i', '.webp', $article['details']['file']);
} else {
$articleFileNameWebp = $article['details']['file'];
}
$article['pathImg'] = PathHelper::pathGenerate(
'article',
[
'factoryUrl' => $afurl,
'collectionUrl' => $acurl,
'file' => 'b_' . $articleFileNameWebp,
]
);
if (!empty($article['commentSchemeImage'])) {
$article['commentSchemeImage'] = PathHelper::pathGenerate(
'article',
[
'factoryUrl' => $afurl,
'collectionUrl' => $acurl,
'file' => 'b_' . $article['details']['commentSchemeImage'],
]
);
}
$alt[] = $article['name'];
foreach ($article['textures'] as $k => $texture) {
$article['textures'][$k]['alias'] = $alt[] = App::trans($texture['alias']);
}
if (!empty($article['details']['variantImage']['texture'])) {
$article['details']['variantImage']['texture'] = ItemHelper::addMainPic(
$article['details']['variantImage']['texture'],
$articleFileNameWebp
);
}
if (!empty($article['details']['variantImage']['picture'])) {
$article['details']['variantImage']['picture'] = ItemHelper::addMainPic(
$article['details']['variantImage']['picture'],
$articleFileNameWebp
);
}
$article = $this->getDiscountsAmount($article);
$coords = [];
if (!empty($article['coordItems'])) {
foreach ($article['coordItems'] as $coord) {
$interiorId = $coord['interior']['id'] ?? null;
if ($interiorId == $row['id']) {
$coords[] = [
'id' => $coord['id'],
'coordX' => $coord['coordX'],
'coordY' => $coord['coordY'],
'typePointer' => $coord['typePointer'],
'interiorId' => $coord['interior']['id'],
'articleId' => $coord['article']['id'],
];
}
}
}
unset($article['coordItems']);
$article['coordItems'] = $coords;
$article['url'] = !empty($article['url']) ? $article['url'] : $article['name'];
if (!empty($buyOrderArticle[$article['id']])) {
$article['orders'] = $buyOrderArticle[$article['id']];
} else {
$article['orders'] = [];
}
$pos = isset($article['collection']['factory']['name'])
? strpos($article['collection']['factory']['name'], '′')
: false;
if ($pos !== false) {
$name = TranslitNameHelper::replacePrime($article['collection']['factory']['name'], false);
$alternateName = TranslitNameHelper::replacePrime(
$article['collection']['factory']['alternateName'],
false
);
$article['collection']['factory']['name'] = $name;
$article['collection']['factory']['alternateName'] = $alternateName;
}
$newElements[$row['id']]['articles'][$n] = ArticleHelper::getTileArticleAddOptions($article);
}
if (!empty($newElements[$row['id']]['articles'])) {
$newElements[$row['id']]['articles'] = array_values($newElements[$row['id']]['articles']);
}
$pos = isset($row['collection']['factory']['name'])
? strpos($row['collection']['factory']['name'], '′')
: false;
if ($pos !== false) {
$name = TranslitNameHelper::replacePrime($row['collection']['factory']['name'], false);
$alternateName = TranslitNameHelper::replacePrime(
$row['collection']['factory']['alternateName'],
false
);
$newElements[$row['id']]['collection']['factory']['name'] = $name;
$newElements[$row['id']]['collection']['factory']['alternateName'] = $alternateName;
}
$newElements[$row['id']]['inIdeaBook'] = in_array($row['id'], $favorites);
$newElements[$row['id']]['url'] = $row['url'];
$newElements[$row['id']]['paths'] = [
'hd' => !empty($row['fileSizeHDY']) ?
PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => 'hd_' . $row['file'],
]
)
: null,
'shd_1080' => !empty($row['fileSizeSHDY'])
? PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => 'shd_' . $row['file'],
]
)
: null,
's_900' => PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => $row['file'],
]
),
];
$newElements[$row['id']]['pathImg'] = PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => $row['file'],
]
);
$alt[] = $row['name'];
foreach ($row['textures'] as $k => $texture) {
$newElements[$row['id']]['textures'][$k]['alias'] = $alt[] = App::trans($texture['alias']);
}
$titleData['i_name'] = $res['numberElement'][$row['id']];
$titleData['numberPhoto'] = $res['numberElement'][$row['id']];
$titleData['minPrice'] = $this->interiorRepository->getArticleMinPriceByInteriorId($row['id']);
} else {
$titleData['a_name'] = $row['name'];
if ($request->get('sample')) {
$newElements[$row['id']]['sampleData'] = $samplesArray[$row['code']] ?? [];
} else {
$newElements[$row['id']]['sampleData'] = null;
}
// todo удалить при первой возможности - вынести из цикла!
$titleData['minPrice'] = $this->articleRepository->getArticleMinPriceById($row['id']);
$newElements[$row['id']]['addUrl'] = App::generateUrl(
'app_buy_orders_list',
[
'articleId' => $row['id'],
]
);
$newElements[$row['id']]['sampleUrl'] = App::generateUrl(
'app_order_sample',
[
'code' => $row['code'],
]
);
$newElements[$row['id']]['collectionUrl'] = App::generateUrl(
'app_collection',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
]
);
$newElements[$row['id']]['factoryUrl'] = App::generateUrl(
'app_catalog',
[
'key' => $furl,
]
);
$newElements[$row['id']]['prc'] = LocaleHelper::getPrice($row);
$newElements[$row['id']]['mea'] = App::trans(LocaleHelper::getMeasure($row));
$newElements[$row['id']]['amount'] = LocaleHelper::getAmount($row);
$newElements[$row['id']]['orders'] = !empty($ordersItems[$row['id']]) ? $ordersItems[$row['id']] : false;
$newElements[$row['id']]['ssLink'] = App::generateUrl(
'app_collection_slideshow',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'type' => 'a',
'elementId' => $row['url'],
]
);
$newElements[$row['id']]['file'] = $row['details']['file'] ?? null;
$newElements[$row['id']]['pathImg'] = PathHelper::pathGenerate(
'article',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => 'b_' . $row['details']['file'] ?? null,
]
);
if ($row['details']['commentSchemeImage']) {
$newElements[$row['id']]['commentSchemeImage'] = PathHelper::pathGenerate(
'article',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => $row['details']['commentSchemeImage'],
]
);
}
if ($row['shape']) {
$newElements[$row['id']]['shape'] = [
'id' => $row['shape']['id'],
'alias' => App::trans($row['shape']['alias']),
];
}
$variantImage = $row['details']['variantImage'] ?? null;
if ($variantImage) {
if ($variantImage['texture'] ?? null) {
$newElements[$row['id']]['variantImage']['texture'] = ItemHelper::addMainPic(
$variantImage['texture'],
$row['details']['file']
);
}
if ($variantImage['picture'] ?? null) {
$newElements[$row['id']]['variantImage']['picture'] = ItemHelper::addMainPic(
$variantImage['picture'],
$row['details']['file']
);
}
}
$filesEdit = $row['details']['fileEdit'] ?? null;
if ($filesEdit) {
foreach ($filesEdit as $fileEdit) {
// генерируем список загружаемых картинок
$newElements[$row['id']]['fileEdit'] = PathHelper::pathGenerate(
'article',
[
'factoryUrl' => $furl,
'collectionUrl' => $curl,
'file' => $fileEdit,
]
);
}
}
$newElements[$row['id']]['imageZipLink'] = null;
$alt[] = $row['name'];
$textures = $row['textures'];
foreach ($textures as $k => $texture) {
$newElements[$row['id']]['textures'][$k]['alias'] = $alt[] = App::trans($texture['alias']);
}
// Формируем metaTitle для артикулов
$titleData['metaTitle'] = $this->buildArticleMetaTitle($row, $collection);
if (!empty($row['interiors'])) {
foreach ($row['interiors'] as $i => $r) {
if (
$r['status'] == 2
|| $r['collection']['status'] != 1
|| $r['collection']['factory']['status'] != 1
) {
if (!empty($newElements[$row['id']]['interiors'][$i])) {
unset($newElements[$row['id']]['interiors'][$i]);
}
continue;
}
$newElements[$row['id']]['interiors'][$i]['url'] = $r['url'];
$newElements[$row['id']]['interiors'][$i]['inIdeaBook'] = in_array($r['id'], $favorites);
if (empty($r['file'])) {
$r['file'] = $r['name'] . '.jpg';
}
if (preg_match('#/f/(.*)/a/#is', App::getRequest()->getUri(), $matches)) {
$url = App::generateUrl('app_collection_slideshow_f', [
'factoryUrl' => $r['collection']['factory']['url'],
'collectionUrl' => $r['collection']['url'],
'filter' => $matches[1],
'type' => 'i',
'elementId' => $r['url'],
]);
} else {
$url = App::generateUrl('app_collection_slideshow', [
'factoryUrl' => $r['collection']['factory']['url'],
'collectionUrl' => $r['collection']['url'],
'type' => 'i',
'elementId' => $r['url'],
]);
}
$r['file'] = StrHelper::toLower($r['file']);
$newElements[$row['id']]['interiors']['setting'] = $r['collection']['settings'];
$newElements[$row['id']]['interiors'][$i]['url'] = $url;
$newElements[$row['id']]['interiors'][$i]['paths'] = [
'hd' => !empty($r['fileSizeHDY']) ?
PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $r['collection']['factory']['url'],
'collectionUrl' => $r['collection']['url'],
'file' => 'hd_' . $r['file'],
]
)
: null,
'shd_1080' => !empty($r['fileSizeSHDY'])
? PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $r['collection']['factory']['url'],
'collectionUrl' => $r['collection']['url'],
'file' => 'shd_' . $r['file'],
]
)
: null,
's_900' => PathHelper::pathGenerate(
'interior',
[
'factoryUrl' => $r['collection']['factory']['url'],
'collectionUrl' => $r['collection']['url'],
'file' => $r['file'],
]
),
];
}
} else {
$newElements[$row['id']]['interiors'] = [];
}
$newElements[$row['id']] = ArticleHelper::getTileArticleAddOptions($newElements[$row['id']]);
}
if (!empty($newElements[$row['id']]['interiors'])) {
unset($newElements[$row['id']]['interiors']['setting']);
// необходимо, чтобы выровнять ключи
$newElements[$row['id']]['interiors'] = array_values($newElements[$row['id']]['interiors']);
}
$metaManager = new MetaManager($titleData, [
'_route' => 'app_collection_slideshow',
'type' => $type,
]);
$newElements[$row['id']]['title'] = html_entity_decode($metaManager->getTitle());
$newElements[$row['id']]['description'] = $metaManager->getDescription();
$newElements[$row['id']]['downloadArticleImageHelpTooltip'] = App::trans('download_help_tooltip');
}
return [
'elements' => $newElements,
'elementsCount' => $elementsCount,
'elementId' => $elementId,
'numberElement' => $res['numberElement'],
];
}
/**
* @param array $elementIdes
* @param ?int $elementId
* @param ?string $load
* @return array
*/
private function getIdes(array $elementIdes, ?int $elementId = null, ?string $load = 'all'): array
{
if (!in_array($load, ['left', 'right', 'all'])) {
$load = 'all';
}
if ($elementId == null) {
$elementId = !empty($elementIdes[0]['id']) ? $elementIdes[0]['id'] : $elementIdes[0] ?? null;
}
$numberElement = [];
$ides = [0 => 0];
foreach ($elementIdes as $k => $row) {
if ($elementId == $row) {
$numberElement[$row] = $k + 1;
if ($load == 'all') {
$ides[] = $row;
}
if ($load == 'left' || $load == 'all') {
if (!empty($elementIdes[$k - 2])) {
$ides[] = $elementIdes[$k - 2];
$numberElement[$elementIdes[$k - 2]] = $k - 1;
}
if (!empty($elementIdes[$k - 1])) {
$ides[] = $elementIdes[$k - 1];
$numberElement[$elementIdes[$k - 1]] = $k;
}
}
if ($load == 'right' || $load == 'all') {
if (!empty($elementIdes[$k + 1])) {
$ides[] = $elementIdes[$k + 1];
$numberElement[$elementIdes[$k + 1]] = $k + 2;
}
if (!empty($elementIdes[$k + 2])) {
$ides[] = $elementIdes[$k + 2];
$numberElement[$elementIdes[$k + 2]] = $k + 3;
}
}
break;
}
}
return [
'ides' => $ides,
'numberElement' => $numberElement,
];
}
private function unsetInactiveArticleInInteriorOrCollection(?array $element): ?array
{
$test = App::isRole('ROLE_TEST');
foreach ($element['articles'] ?? [] as $key => $article) {
if ($test) {
if ($article['collection']['status'] == 2) {
unset($element['articles'][$key]);
}
} else {
if ($article['collection']['status'] != 1) {
unset($element['articles'][$key]);
}
}
}
return $element;
}
private function addInfoAboutAvailableInCountryOfFactory(array $collection, array &$newElement): void
{
if (!($collection['factory']['country']['code'] ?? null)) {
return;
}
switch (StrHelper::toLower($collection['factory']['country']['code'])) {
case 'it':
$newElement['in_stock'] = $this->translator->trans('in_stock_italy');
return;
case 'es':
$newElement['in_stock'] = $this->translator->trans('in_stock_spain');
return;
case 'ge':
$newElement['in_stock'] = $this->translator->trans('in_stock_germany');
return;
case 'ma':
$newElement['in_stock'] = $this->translator->trans('in_stock_morocco');
return;
case 'pt':
$newElement['in_stock'] = $this->translator->trans('in_stock_portugal');
return;
}
}
public function getCountryUrl(array $collection): string
{
if (empty(App::getCountryList()[StrHelper::toLower($collection['factory']['country']['code'])])) {
$countryEntity = $this->listCountryRepository->getCountry($collection['factory']['country']['code']);
$countryKey = '';
if ($countryEntity) {
$countryKey = $countryEntity->getAlias();
}
} else {
$countryKey = App::getCountryList()[StrHelper::toLower($collection['factory']['country']['code'])]['alias'];
}
if (!$countryKey) {
return '';
}
$countryKey = $this->filterRepository->getKeyByLeftMenu($countryKey);
return App::generateUrl('app_catalog', ['key' => $countryKey]);
}
/**
* @throws ArticleNotAvailableNowException
*/
private function checkAvailableArticle(array $element): void
{
if ($element['delivery']['id'] === ArticleStateEnum::STATE_ITEM_DISCONTINUED) {
throw new ArticleNotAvailableNowException();
}
}
/**
* Получение информации о вариантах скидок (сколько-то от палеты и тд)
* @param $article
* @return array
* @throws Exception
*/
public function getDiscountsAmount($article): array
{
// очищаем массив, чтобы избежать дублирования при повторном вызове
$article['discountsAmount'] = [];
// добавляем объект цены для js
$price = LocaleHelper::getPrice($article);
$woVATPrice = LocaleHelper::isWithoutVATPrice($price);
$article['discountsAmount'][] = $this->getDiscountPriceArray($price, 0.0, $woVATPrice ?: $price, 0);
return $this->getMoreDiscountsAmount($article);
}
private function getMoreDiscountsAmount(array $article): array
{
if (empty($article['priceDiscounts'])) {
return $article;
}
foreach ($article['priceDiscounts'] as $k => $discount) {
if ($discount == null) {
continue;
}
$priceDiscount = LocaleHelper::getPriceDiscount($discount, ['measureId' => $article['measure']['id']]);
if (
$k == 0
&& $article['multiplePallet'] == 1
&& $article['packagingCount'] >= $priceDiscount['amount']
) {
$article['discountsAmount'] = [];
} else {
$article['discountsAmount'][count($article['discountsAmount']) - 1]['endAmount'] = $priceDiscount['amount'];
}
$woVATPrice = LocaleHelper::isWithoutVATPrice($priceDiscount['price']);
$article['discountsAmount'][] = $this->getDiscountPriceArray(
(float)$priceDiscount['price'],
(float)$priceDiscount['amount'],
(float)($woVATPrice ?: $priceDiscount['price']),
$discount['fold']
);
}
return $article;
}
private function getDiscountPriceArray(float $price, float $amount, float $woVATPrice, $fold): array
{
return [
'price' => LocaleHelper::floatSignWithOutPostfixZeros($price),
'startAmount' => LocaleHelper::floatSignWithOutPostfixZeros($amount),
'woVATPrice' => $woVATPrice,
'fold' => $fold,
];
}
public function prepareDiscountAmountForEachArticle(?array $elements): array
{
foreach ($elements as &$element) {
$element = $this->getDiscountsAmount($element);
}
return $elements;
}
/**
* Формирование metaTitle для артикулов
* @param array $article
* @return string
*/
private function buildArticleMetaTitle(array $row, array $collection): string
{
//- стиль
//- фактура
//- соответствие цвету
//- материалы "пробка" и "агломерат"
//- форма (кроме квадрата, прямоугольника и неправильной)
//- размеры
//- страну производства
$locale = App::getCurLocale();
if ($row['type']['id'] != 113) {
$meta = [$row['type']['name']];
} elseif (!empty($row['colors'][0])) {
$alias = $row['colors'][0]['alias'];
$meta = [
$this->filterRepository->getSameSingleByLeft(
$locale,
$alias
)
];
} else {
$meta = [];
}
$styles = $row['styles'];
foreach ($styles as $k => $style) {
$meta[] = App::trans($style['alias']);
}
$facture = [];
foreach ($row['textures'] as $k => $texture) {
//to-do добавить название группы
$newElements[$row['id']]['textures'][$k]['alias'] = $alt[] = $facture[] = App::trans($texture['alias']);
}
if (!empty($facture)) {
$result = implode(', ', $facture);
if (!in_array($locale, ['en', 'nl'])) {
$result = StrHelper::toLower($this->translator->trans('left_menu_effect', [], null, $locale)) .
(in_array(
$locale,
['de', 'fi', 'sv', 'da', 'no', 'pt']
) ? ': ' : ' ') . StrHelper::toLower($result);
} else {
$result .= ' ' . StrHelper::toLower($this->translator->trans('left_menu_effect', [], null, $locale));
}
$meta[] = $result;
}
if ($row['type']['id'] != 113) {
$colors = $row['colors'];
foreach ($colors as $k => $color) {
$meta[] = App::trans($color['alias']);
}
}
if (in_array($row['material']['id'], [17, 32])) {
$meta[] = $row['material']['name'];
}
if (!in_array($row['shape']['id'], [1, 4, 9,])) {
$meta[] = $row['shape']['name'];
}
$metaTitle = implode(', ', $meta);
$metaTitle = StrHelper::ucFirst($metaTitle);
if (!empty($row['sizeX'])) {
$metaTitle .= ' ' . round($row['sizeX']) . 'x' . round($row['sizeY']);
}
$metaTitle .= ' (' . App::trans($collection['factory']['country']['alias']) . ')';
return $metaTitle;
}
}