src/WebBundle/Service/SphinxSearcherService.php line 1520

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Service;
  3. use Doctrine\ORM\EntityManager;
  4. use Exception;
  5. use Symfony\Component\DependencyInjection\ContainerInterface;
  6. use Symfony\Component\Translation\Translator;
  7. use WebBundle\Entity\ListMaterial;
  8. use WebBundle\Entity\ListMeasure;
  9. use WebBundle\Helper\App;
  10. use WebBundle\Helper\CurrencyRateHelper;
  11. use WebBundle\Helper\HideFactoryCountriesHelper;
  12. use WebBundle\Helper\LocaleHelper;
  13. use WebBundle\Helper\StrHelper;
  14. use WebBundle\Repository\FilterRepository;
  15. use WebBundle\Repository\ListMaterialRepository;
  16. use WebBundle\Repository\ListMeasureRepository;
  17. class SphinxSearcherService
  18. {
  19.     private array $materials = [];
  20.     /** @required */
  21.     public ListMeasureRepository $listMeasureRepository;
  22.     /** @required */
  23.     public ListMaterialRepository $listMaterialRepository;
  24.     /** @var EntityManager */
  25.     private $em;
  26.     /** @var sphinxQLService $sphinxQL */
  27.     private $sphinxQL;
  28.     /** @var Translator $translator */
  29.     private $translator;
  30.     protected array $articlesId = [];
  31.     protected array $subFilters = [];
  32.     private FilterRepository $filterRepo;
  33.     /**
  34.      * @param ContainerInterface $container
  35.      * @param FilterRepository $filterRepository
  36.      * @throws Exception
  37.      */
  38.     public function __construct(ContainerInterface $containerFilterRepository $filterRepository)
  39.     {
  40.         $this->filterRepo $filterRepository;
  41.         $this->em $container->get('doctrine');
  42.         $this->sphinxQL $container->get('sphinx_ql');
  43.         $this->translator $container->get('translator');
  44.     }
  45.     /**
  46.      * @param ?array $data - данные для выборки
  47.      * @param ?int $limit - если 0 то вывести все
  48.      * @param ?bool $withSchema - если true, то в поиске подбирать артикулы со схематичным изображением
  49.      * @param ?bool $full
  50.      * @param ?bool $getCount
  51.      * @return array
  52.      * @throws Exception
  53.      */
  54.     public function searchSphinx(
  55.         ?array $data = [],
  56.         ?int $limit 0,
  57.         ?bool $withSchema false,
  58.         ?bool $full false,
  59.         ?bool $getCount false
  60.     ): array {
  61.         $this->sphinxQL->clear();
  62.         ini_set('memory_limit''2048M');
  63.         $dataReview = [];
  64.         $fields = [
  65.             'c_id',
  66.             'coll',
  67.             'border_grey',
  68.             'a_id',
  69.             'type_filter',
  70.             'c_name',
  71.             'c_status',
  72.             'c_header',
  73.             'c_release_year',
  74.             'c_url',
  75.             'c_awards',
  76.             'c_exhibition',
  77.             'c_accessible',
  78.             'f_name',
  79.             'f_id',
  80.             'f_url',
  81.             'rating_month',
  82.             'publish_date',
  83.             'country',
  84.             'country_code',
  85.             'author',
  86.             'a_name',
  87. // Чистим от не нужных полей
  88.             'size_x',
  89.             'size_y',
  90.             'tolsch',
  91.             //для вывода возможных толщин
  92.             'sliding',
  93.             'a_style',
  94.             'measure',
  95.             'type',
  96.             'file',
  97.             'fs_x',
  98.             'fs_y',
  99.             'is_main',
  100.             'c_express_sample',
  101.             'price_sort',
  102.             //'square',
  103.             'c_material',
  104.             'process',
  105.             'express_sample',
  106.             'factory',
  107.             'u_id',
  108.             'thin_granite',
  109.             'attr_data',
  110.             //.i as interior || .i as i не получаем лишние данные если не будет facet еще быстрее получаем только a_id и дальше к бд (тест скорости провести)
  111.             'size_big',
  112.             'glazed_granite',
  113.             'thick_granite',
  114.             'publish_period',
  115.             'dyed_in_mass',
  116.             'color_body',
  117.             'c_designer_ids',
  118.             'monochrome',
  119.             'prc_count',
  120.             'prc_vote',
  121.             'reviews',
  122.             'a_texture',
  123.             'a_motive',
  124.             'surface',
  125.             'shape',
  126.             'color',
  127.             'material',
  128.             'a_stone_texture',
  129.             'a_motiv',
  130.             'typecoll',
  131.             'a_head',
  132.             'sid',
  133.             'styleid',
  134.             'styleida',
  135.             'sort',
  136.             'is_head',
  137.             'apply_id',
  138.             'c_apply',
  139.             'using',
  140.             'pr_status',
  141.             'edge_type',
  142.             'off_shade',
  143.         ];
  144.         if (isset($data['searchFilter']['getTopMonth'])) {
  145.             $fields[] = 'c_pop30';
  146.             $fields[] = 'c_last_pop30';
  147.         } elseif (isset($data['searchFilter']['getTopWeek'])) {
  148.             $fields[] = 'c_pop7';
  149.             $fields[] = 'c_last_pop7';
  150.         }
  151.         $buildingMixtureOff false;
  152.         // тут костыль для скольжения https://te.remote.team/#/discus/7AF53097-7533-5034-0808-93CF8BDB1E75/
  153.         // Не бывает матовой поверхности с коэффициентом противоскольжения (если и бывает, то это просто ошибка в свойствах артикула)
  154.         // todo излишнее так как sliding= '999.a.sliding
  155.         if (
  156.             !empty($data['searchFilter']['getSurfaces'])
  157.             && !empty($data['searchFilter']['sliding'])
  158.             && count($data['searchFilter']['sliding']) == 4
  159.         ) {
  160.             $data['searchFilter']['getSurfaces'][] = 8;
  161.             unset($data['searchFilter']['sliding']);
  162.         }
  163.         // фильтр по антислипу sliding на самом деле getSurfaces
  164.         // todo лишнее
  165.         if (!empty($data['searchFilter']['sliding'])) {
  166.             foreach ($data['searchFilter']['sliding'] as $row) {
  167.                 $data['searchFilter']['getSurfaces'][] = (int)('999' $row);
  168.             }
  169.             unset($data['searchFilter']['sliding']);
  170.         }
  171.         // На основании вот этой просьбы https://te.remote.team/#/discus/4B853CC1-9B65-BD60-F896-352327BC5F2C/
  172.         if (!empty($data['searchFilter']['factory']) && count($data['searchFilter']) == 1) {
  173.             $withSchema true;
  174.         }
  175.         if (!App::isRole('ROLE_TEST')) {
  176.             $this->sphinxQL->addWhere('c_test_access != 1');
  177.             $this->sphinxQL->addWhere('f_test_access != 1');
  178.         }
  179.         if (!empty($data['HideFactory'])) {
  180.             $this->sphinxQL->addWhere('f_id NOT IN (?)'$data['HideFactory']);
  181.         } elseif (HideFactoryCountriesHelper::length() > 0) {
  182.             $this->sphinxQL->addWhere('f_id NOT IN (?)'HideFactoryCountriesHelper::codes());
  183.         }
  184.         $country App::getCurCountry();
  185.         $measure = !empty($data['measure']) ? $data['measure'] : LocaleHelper::getUserMeasure();
  186.         $priceFields $this->getPriceFields(LocaleHelper::getCur(), $country$measure);
  187.         // для автоматической простановки фильтров
  188.         $dataArticles = [
  189.             'getPrstatus' => 'pr_status'// код акции
  190.             'getTypes' => 'type'// код вида изделия
  191.             'getTypeUsings' => 'using'// код назначения
  192.             'getCountry' => 'country'// код страны
  193.             'getPrcateg' => 'pr_status'// код акции
  194.             'getMaterials' => 'material'// код материала
  195.             'getCostCategory' => $priceFields[3],//'a_price_cat', // код категории цены
  196.             'getEdgeType' => 'edge_type'// тип края
  197.             'offShade' => 'off_shade'// разнотон (моноколор)
  198.             'getStyles' => 'sid'// код стиля
  199.             'getSurfaces' => 'surface'// код типа
  200.             'getFacturas' => 'a_texture'// код фактуры
  201.             'getStone' => 'a_stone_texture'// код фактуры камня
  202.             'getColors' => 'color'// код цветов
  203.             'shape' => 'shape'// код формы
  204.             'motive' => 'a_motive'// мотив рисунка
  205.             'motiv' => 'a_motiv'// мотив рисунка
  206.             'pei' => 'pei',
  207.         ];
  208. //        $fromCountArr = [
  209. //            //Filter => sphinx_filds
  210. //            'getStyles' => 'sid', // код стиля
  211. //            'getSurfaces' => 'surface', // код типа
  212. //            'getFacturas' => 'a_texture', // код фактуры
  213. //            'getStone' => 'a_stone_texture', // код фактуры камня
  214. //            'getColors' => 'color', // код цветов
  215. //            'shape' => 'shape', // код формы
  216. //            'motive' => 'a_motive', // мотив рисунка
  217. //            'motiv' => 'a_motiv', // мотив рисунка
  218. //            'inside' => $priceFields[0],
  219. //            'discontinued' => 'typecoll',
  220. //            'expressSample' => 'express_sample',
  221. //            'getAwards' => 'c_awards',
  222. //            'exhibition' => 'c_exhibition',
  223. //            'size_x' => 'size_x',
  224. //            'size_y' => 'size_y',
  225. //            'tolsch' => 'thick',
  226. //            'thick' => 'thick',
  227. //            'material' => 'material',
  228. //            'getTypeUsings' => 'using',
  229. //            'factory' => 'factory',
  230. //            'bm' => 'u_id',
  231. //            'c_id' => 'c_id',
  232. //            'getThinGranite' => 'thin_granite',
  233. //            'size_big' => 'size_big',
  234. //            'getGlazedGranit' => 'glazed_granite',
  235. //            'getThickGranite' => 'thick_granite',
  236. //            'searchPeriod' => 'publish_period',
  237. //            'releaseYear' => 'c_release_year',
  238. //            'reviews' => 'reviews',
  239. //            'dyedInMass' => 'dyed_in_mass',
  240. //            'colorBody' => 'color_body',
  241. //            'sliding' => 'sliding',
  242. //            'getUsings' => 'apply_id',
  243. //            'getDesigner' => 'c_designer_ids',
  244. //            'monochrome' => 'monochrome',
  245. //        ];
  246.         //Добавим поля интерьера первые найденный тогда сфинкс вернет сразу пустую строку и не нужно будет делать проверку и цикл
  247.         $interiorFilds = [
  248.             'attr_data.i[0].i_name as i_name',
  249.             'attr_data.i[0].i_id as i_id',
  250.             'attr_data.i[0].i_rating as i_rating',
  251.             'attr_data.i[0].i_monochrome as i_monochrome',
  252.             'attr_data.i[0].i_status as i_status',
  253.             'attr_data.i[0].i_file as i_file',
  254.             'attr_data.i[0].i_wall_and_floor as i_wall_and_floor',
  255.             'attr_data.i[0].i_style as i_style',
  256.             'attr_data.i[0].i_texture as i_texture',
  257.             'attr_data.i[0].fsi_x as fsi_x',
  258.             'attr_data.i[0].fsi_y as fsi_y',
  259.         ];
  260.         //поля которые перенесены в attr_data что позволило сократить таблицу до артикулов проверить
  261.         $mvaFields = [
  262.             'color',
  263.             'material',
  264.             'a_motive',
  265.             'a_texture',
  266.             'designer',
  267.             'edge_type',
  268.             'a_motiv',
  269.             'shape',
  270.             'a_stone_texture',
  271.             'style',
  272.             'surface',
  273.             'texture',
  274.             'a_head',
  275.             'sid',
  276.             'styleida',
  277.             'styleid',
  278.             'sort',
  279.             'i_style',
  280.             'c_apply',
  281.             'apply_id',
  282.             'typecoll',
  283.             'i_rating',
  284.             'i_id',
  285.             'is_head',
  286.             'fsi_x',
  287.             'fsi_y',
  288.             'i_name_hash',
  289.             'i_file_hash',
  290.             'i_type',
  291.             'i_status',
  292.             'i_texture',
  293.             'i_monochrome',
  294.             'i_wall_and_floor',
  295.             'using',
  296.             'type',
  297.         ];
  298.         //вычитаем поля если они attr_data добавляются через $dataAttrFields
  299.         // $plusFields = array_diff($plusFields, $attrData);
  300.         $fields array_unique(array_merge($interiorFilds$fields$priceFields));
  301. //        App::debugExit($fields);
  302.         if (empty($data['total_found'])) {
  303.             $this->sphinxQL->setFrom('article'$fields);
  304.         } else {
  305.             $this->sphinxQL->setFrom('article''coll'); //todo тут должна появиться новая таблица
  306.         }
  307.         if (!empty($data['searchFilter']['inside'])) {
  308.             $this->sphinxQL->addWhere($priceFields[0] . ' > 0.0');
  309.             $this->sphinxQL->addWhere('delivery <> 6');
  310.         } elseif (!empty($data['searchFilter']['discontinued'])) {
  311.             $this->sphinxQL->addWhere('ANY(typeColl) in (2) ');
  312.         } else {
  313.             $this->sphinxQL->addWhere('ANY(typeColl) in (1)');
  314.             if (!(!empty($data['searchFilter']['factory']) && count($data['searchFilter']) == 1)) {
  315.                 $this->sphinxQL->addWhere($priceFields[0] . ' > 0.0');
  316.                 $this->sphinxQL->addWhere('c_status = 1');
  317.             } else {
  318.                 $this->sphinxQL->addWhere('c_status IN (1, 3)');
  319.             }
  320.         }
  321.         // принято решение, если выбран стиль, то отбираем сразу по фонам декорам панно
  322.         // https://te.remote.team/#/discus/85E0842C-BCDE-D6E6-7EA4-2DB50BB404EC/
  323.         if (
  324.             !empty($data['searchFilter']['getStyles']) &&
  325.             empty($data['searchFilter']['getTypes']) &&
  326.             empty($data['searchFilter']['inside'])
  327.         ) {
  328.             $data['searchFilter']['getTypes'] = [111310624122128]; //todo нужно перенести в индекс
  329.         }
  330.         //TODO Удалить раз схемы навсегда улетают
  331.         //        if (
  332.         //            !$withSchema && (
  333.         //                empty($data['searchFilter']['getTypes']) ||
  334.         //                array_intersect($data['searchFilter']['getTypes'], [1, 24, 113, 122])
  335.         //            ) &&
  336.         //            empty($data['searchFilter']['size_x']) &&
  337.         //            empty($data['searchFilter']['size_y']) &&
  338.         //            empty($data['searchFilter']['size_z']) &&
  339.         //            empty($data['searchFilter']['motiv'])
  340.         //        ) {
  341.         //            $this->sphinxQL->addWhere('scheme = ?', 0);
  342.         //        }
  343.         $this->sphinxQL->addWhere('scheme = ?'0);
  344.         // ставим фильтры
  345.         if (!empty($data['searchFilter'])) {
  346.             if (!empty($data['searchFilter']['expressSample'])) {
  347.                 if (
  348.                     !empty($data['searchFilter']['inside']) ||
  349.                     count($data['searchFilter']) > && empty($data['searchFilter']['factory']) ||
  350.                     count($data['searchFilter']) > && !empty($data['searchFilter']['factory'])
  351.                 ) {
  352.                     $this->sphinxQL->addWhere("express_sample = 1");
  353.                 } else {
  354.                     $this->sphinxQL->addWhere("c_express_sample = 1");
  355.                 }
  356.             }
  357.             // если getAwards, то просто проверяем наличие наград и все, без уточнений
  358.             if (!empty($data['searchFilter']['getAwards'])) {
  359.                 $this->sphinxQL->addWhere("c_awards is not null");
  360.             }
  361.             // Если exhibition, то просто проверяем наличие выставок и все,
  362.             // без уточнений. Их фильтруем потом дополнительно
  363.             if (!empty($data['searchFilter']['exhibition'])) {
  364.                 $this->sphinxQL->addWhere("c_exhibition <> ''");
  365.             }
  366.             // отдельно фильтр для дизайнеров, с заготовкой под ID
  367.             if (!empty($data['searchFilter']['getDesigner'])) {
  368.                 // 1 имя, 0 это Id
  369.                 $designerName '';
  370.                 $designerId $data['searchFilter']['getDesigner'][0];
  371.                 // поставил LIKE поиск по имени дизайнера + поиск по ID
  372.                 $this->sphinxQL->addWhere("MATCH('(@c_designer_ids $designerId{$designerName}')");
  373.                 unset($data['searchFilter']['getDesigner']);
  374.             }
  375.             if (!empty($data['searchFilter']['size_x'])) {
  376.                 $this->sphinxQL->addWhere(
  377.                     'size_x >= ?',
  378.                     str_replace(',''.'$data['searchFilter']['size_x'][0] * 100)
  379.                 );
  380.                 $buildingMixtureOff true;
  381.             }
  382.             if (!empty($data['searchFilter']['size_y'])) {
  383.                 $this->sphinxQL->addWhere(
  384.                     'size_y >= ?',
  385.                     str_replace(',''.'$data['searchFilter']['size_y'][0] * 100)
  386.                 );
  387.                 $buildingMixtureOff true;
  388.             }
  389.             if (!empty($data['searchFilter']['tolsch'])) {
  390.                 $this->sphinxQL->addWhere(
  391.                     'tolsch >= ?',
  392.                     str_replace(',''.'$data['searchFilter']['tolsch'][0] * 100)
  393.                 );
  394.                 $buildingMixtureOff true;
  395.             }
  396.             if (!empty($data['searchFilter']['size_x2'])) {
  397.                 $this->sphinxQL->addWhere(
  398.                     'size_x <= ?',
  399.                     str_replace(',''.'$data['searchFilter']['size_x2'][0] * 100)
  400.                 );
  401.                 if (empty($data['searchFilter']['size_x'])) {
  402.                     $this->sphinxQL->addWhere('size_x > ?'0);
  403.                 }
  404.                 $buildingMixtureOff true;
  405.             }
  406.             if (!empty($data['searchFilter']['size_y2'])) {
  407.                 $this->sphinxQL->addWhere(
  408.                     'size_y <= ?',
  409.                     str_replace(',''.'$data['searchFilter']['size_y2'][0] * 100)
  410.                 );
  411.                 if (empty($data['searchFilter']['size_y'])) {
  412.                     $this->sphinxQL->addWhere('size_y > ?'0);
  413.                 }
  414.                 $buildingMixtureOff true;
  415.             }
  416.             if (!empty($data['searchFilter']['tolsch2'])) {
  417.                 $this->sphinxQL->addWhere(
  418.                     'tolsch <= ?',
  419.                     str_replace(',''.'$data['searchFilter']['tolsch2'][0] * 100)
  420.                 );
  421.                 if (empty($data['searchFilter']['tolsch'])) {
  422.                     $this->sphinxQL->addWhere('tolsch > ?'0);
  423.                 }
  424.                 $buildingMixtureOff true;
  425.             }
  426.             // специально для приложений
  427.             if (!empty($data['searchFilter']['prMinFrom'])) {
  428.                 $this->sphinxQL->addWhere(
  429.                     'pr_min <= ?',
  430.                     str_replace(',''.'$data['searchFilter']['prMinFrom'][0] * 100)
  431.                 );
  432.             }
  433.             if (!empty($data['searchFilter']['prMinTo'])) {
  434.                 $this->sphinxQL->addWhere(
  435.                     'pr_min >= ?',
  436.                     str_replace(',''.'$data['searchFilter']['prMinTo'][0] * 100)
  437.                 );
  438.             }
  439. //todo удалить после тестов перенести логику наверх
  440.             if (!empty($data['searchFilter']['shape'])) {
  441. //                if (in_array(10, $data['searchFilter']['shape'])) {
  442. //                    unset($data['searchFilter']['shape'][array_search(10, $data['searchFilter']['shape'])]);
  443. //                    $this->sphinxQL->addWhere('module = ?', 1);
  444. //                }
  445.                 if (!count($data['searchFilter']['shape'])) {
  446.                     unset($data['searchFilter']['shape']);
  447.                 }
  448.             }
  449.             // фильтр окрашен по color body //нужно добавить в материал иначе идет только через AND
  450.             if (!empty($data['searchFilter']['colorBody'])) {
  451.                 $data['searchFilter']['getMaterials'][] = 999;
  452.                 //  $this->sphinxQL->addWhere("color_body = ?", $data['searchFilter']['colorBody']);
  453.             }
  454.             if (!empty($data['searchFilter']['getColors']) && in_array(99$data['searchFilter']['getColors'])) {
  455.                 $this->sphinxQL->addWhere('ANY(color) in (?)'99);
  456.                 unset($data['searchFilter']['getColors'][array_search(99$data['searchFilter']['getColors'])]);
  457.                 if (empty($data['searchFilter']['getColors'])) {
  458.                     unset($data['searchFilter']['getColors']);
  459.                 }
  460.             }
  461.             // если есть фильтры, то добавляем их к запросу
  462.             foreach ($data['searchFilter'] as $key => $row) {
  463.                 if (!empty($dataArticles[$key])) {
  464.                     // отключаем фильтр getPrcateg и ориентируемся на баланс
  465.                     if (trim($key) == 'getPrcateg') {
  466.                         continue;
  467.                     }
  468.                     //тут проставим $mvaFields чтобы искать в MVA any|all
  469.                     if (in_array($dataArticles[$key], $mvaFields)) {
  470.                         $dataArticles[$key] = ' ANY(' $dataArticles[$key] . ')';
  471.                     }
  472.                     $this->sphinxQL->addWhere($dataArticles[$key] . ' IN (?)'$row);
  473.                 }
  474.             }
  475.             // фильтр окрашен в массе
  476.             if (!empty($data['searchFilter']['dyedInMass'])) {
  477.                 $this->sphinxQL->addWhere('dyed_in_mass = 1');
  478.             }
  479.             // !!! теперь если выбран фильтр применения показываем только интерьеры
  480.             // для применения работает немного иначе если более одного признака то идёт наследование от коллекции,
  481.             // но при этом надо не показывать интерьеры, которые не соответствуют применению
  482.             if (!empty($data['searchFilter']['getUsings'])) {
  483.                 if (!empty($data['searchFilter']['getUsings'])) {
  484.                     // вернул выборку по ID иначе показывает все из "применения" без фильтрации.
  485.                     $this->sphinxQL->addWhere('ANY(apply_id) IN (?)'$data['searchFilter']['getUsings']);
  486.                 }
  487.                 $this->sphinxQL->addWhere('c_accessible <> 1');
  488.             }
  489.             // фильтр по фабрике
  490.             if (!empty($data['searchFilter']['factory'])) {
  491.                 $this->sphinxQL->addWhere('factory = \'' $data['searchFilter']['factory'][0] . '\'');
  492.             }
  493.             // фильтр по фабрике
  494.             if (!empty($data['searchFilter']['bm'])) {
  495.                 $bmId $data['searchFilter']['bm'];
  496.                 $bmId is_array($bmId) ? $bmId[0] : $bmId;
  497.                 $this->sphinxQL->addWhere('u_id = ' $bmId);
  498.             }
  499.             // фильтр по id коллекций
  500.             if (!empty($data['searchFilter']['c_id'])) {
  501.                 $this->sphinxQL->addWhere('c_id IN (?)'$data['searchFilter']['c_id']);
  502.             }
  503.         }
  504.         // тонкий керамогранит
  505.         if (!empty($data['searchFilter']['getThinGranite'])) {
  506.             $this->sphinxQL->addWhere('thin_granite = ?'1);
  507.             $buildingMixtureOff true;
  508.         }
  509.         // фильтр большого размера плитки
  510.         if (!empty($data['searchFilter']['size_big'])) {
  511.             $this->sphinxQL->addWhere('size_big = ?'1);
  512.             $buildingMixtureOff true;
  513.         }
  514.         // глазурированный/неглазурированный керамогранит
  515.         if (!empty($data['searchFilter']['getGlazedGranit'])) {
  516.             $this->sphinxQL->addWhere('glazed_granite = ?'$data['searchFilter']['getGlazedGranit']);
  517.         }
  518.         if ($country == 'ru' || $buildingMixtureOff) {
  519.             $this->sphinxQL->addWhere('c_id != ?'3245628);
  520.         }
  521.         // утолщенный керамогранит
  522.         if (!empty($data['searchFilter']['getThickGranite'])) {
  523.             $this->sphinxQL->addWhere('thick_granite = ?'$data['searchFilter']['getThickGranite']);
  524.         }
  525.         // Если новинки, то выводим только коллекции за месяц
  526.         //Семраш пишет не может сканировать страницу новинок
  527.         //https://te2.remote.team/discus/35DEFA01-C136-0EA2-DB72-E8999812EBFC
  528.         if (isset($data['searchFilter']['getTop'])) {
  529.             $this->sphinxQL->addWhere('ANY(publish_period) = ?'4);
  530.         }
  531.         // выборки за период
  532.         if (isset($data['searchPeriod'])) {
  533.             $this->sphinxQL->addWhere('ANY(publish_period) = ?'$data['searchPeriod']);
  534.         }
  535.         $dateSort 'publish_date DESC';
  536.         // фильтрация по году выпуска
  537.         if (!empty($data['searchFilter']['releaseYear'])) {
  538.             $years = [];
  539.             foreach ($data['searchFilter']['releaseYear'] as $year) {
  540.                 if (strlen($year) > 4) {
  541.                     $y substr($year04);
  542.                     do {
  543.                         $y--;
  544.                         $years[] = $y;
  545.                     } while ($y 2013);
  546.                 } elseif ($year == 999) {
  547.                     $years[] = date('Y');
  548.                 } else {
  549.                     $years[] = $year;
  550.                 }
  551.             }
  552.             if (count($years) > 0) {
  553.                 $this->sphinxQL->addWhere('c_release_year IN (?)'$years);
  554.             }
  555.         }
  556.         // фильтрация по средней оценке отзывов
  557.         if (!empty($data['searchFilter']['reviews'])) {
  558.             $this->sphinxQL->addWhere('reviews IN (?)'$data['searchFilter']['reviews']);
  559.             if ($this->getSearchSortId() == 0) {
  560.                 $data['searchSort'] = 6;
  561.             }
  562.         }
  563.         // учитываем сортировку в запросе
  564.         if (isset($data['searchFilter']['getTopMonth'])) {
  565.             $searchSort 'c_pop30 DESC';
  566.         } elseif (isset($data['searchFilter']['getTopWeek'])) {
  567.             $searchSort 'c_pop7 DESC';
  568.         } else {
  569.             $searchSort 'rating DESC';
  570.         }
  571.         if (!empty($data['searchFilter']['getCostCategory']) && $this->getSearchSortId() == 0) {
  572.             $searchSort 'price_sort ASC';
  573.         }
  574.         if (!empty($data['searchFilter'][''])) {
  575.             unset($data['searchFilter']['']);
  576.         }
  577.         // определяем тип минимальной цены
  578.         $minTypeAll false;
  579.         if (
  580.             (count($data['searchFilter']) == || !empty($data['searchFilter']['factory'])
  581.                 && count($data['searchFilter']) == 1) && !$getCount
  582.         ) {
  583.             $minTypeAll true;
  584.             // Если нет фильтров ищем только по фонам мозаике декору
  585.             // Ага, а если ищем зеленный, то выводим красный :)
  586.             //   $this->sphinxQL->addWhere('ANY(type) IN (?)', [1, 24, 113, 122, 27, 106, 64, 128, 0]);
  587.         }
  588.         // https://te.remote.team/#/discus/BDBD8973-1F54-3B16-99ED-8656AEFC1105/
  589.         // убрал совсем сортировку по полю price_euro
  590.         if (
  591.             !empty($data['searchFilter']['getTypes']) && !array_intersect(
  592.                 (array)$data['searchFilter']['getTypes'],
  593.                 [124113122106]
  594.             )
  595.         ) {
  596.             $sort 'price_sort ASC';
  597.         } else {
  598.             $sort $priceFields[4] . ' ASC';
  599.         }
  600.         $searchSortLimit false;
  601.         if (!empty($data['searchSort'])) {
  602.             switch ($data['searchSort']) {
  603.                 case 2:
  604.                     // по цене
  605.                     $searchSort false;
  606.                     break;
  607.                 case 3:
  608.                     // по дате
  609.                     $searchSort 'publish_date DESC';
  610.                     break;
  611.                 case 4:
  612.                     // по алфавиту
  613.                     $searchSort 'c_name ASC';
  614.                     break;
  615.                 case 5:
  616.                     // по популярности за месяц
  617.                     $searchSort 'rating_month DESC';
  618.                     break;
  619.                 case 6:
  620.                     // по отзывам
  621.                     $searchSort 'prc_star DESC';
  622.                     $searchSortLimit 'prc_count DESC';
  623.                     break;
  624.             }
  625.         }
  626.         if (empty($data['total_found'])) {
  627.             if ($searchSort) {
  628.                 $this->sphinxQL->setOrder($searchSort);
  629.             }
  630.             $this->sphinxQL
  631.                 ->setOrder('sort DESC')
  632.                 ->setOrder(
  633.                     $searchSortLimit $searchSortLimit $sort
  634.                 //цена в приоритете она создает коллекцию и минимальную ее цену
  635.                 ->setOrder('max_is_head DESC'//сортирует только по строкам max_is_head"
  636.                 ->setOrder($dateSort);
  637.         }
  638.         if (!empty($data['total_found'])) {
  639.             $this->sphinxQL->setLimit(1)
  640.                 ->setGroup('coll');
  641.             $rows $this->sphinxQL->getQuery()->fetchAllAssociative();
  642.             $totalFound $this->sphinxQL->getTotalFound();
  643.             return ['total_found' => $totalFound];
  644.         }
  645.         $this->subFilters $this->filterRepo->getFiltersSubRelation(false);
  646.         if (empty($data['limit'])) {
  647.             $this->sphinxQL->setLimit(SphinxQLService::MAX_MATCHES);
  648.             if (empty($data['searchFilter']['inside'])) {
  649.                 $this->sphinxQL->setGroup('a_id');//, i_id, sid, styleid, styleida
  650.             }
  651.         } else {
  652.             $this->sphinxQL->setLimit($data['limit'])
  653.                 ->setGroup('coll');
  654.         }
  655.         if (!empty($data['real'])) {
  656.             $this->sphinxQL->setOption('max_matches=200000');
  657.             $this->sphinxQL->setLimit(200000);
  658.         }
  659.         $ed = [];
  660.         $listMeasure $this->em->getRepository('WebBundle:ListMeasure')->findBy(['hide' => false]);
  661.         /** @var ListMeasure $row */
  662.         foreach ($listMeasure as $row) {
  663.             $ed[$row->getId()] = $row->getAlias() != null
  664.                 $this->translator->trans($row->getAlias())
  665.                 : $row->getName();
  666.         }
  667.         //дополнительные свойства
  668.         $collections = ['i_names' => [], 'a_names' => []];
  669.         $num 0;
  670.         $rows $this->sphinxQL->getQuery()->fetchAllAssociative();
  671.         if ($getCount) {
  672.             $calculate = [];
  673.             //Создаем привязку фильтра к нашим полям для подсчета
  674.             $aFiltersOnlyNoChilds $this->filterRepo->getListForSynchCountFilters([]);
  675.             $realFilterProperty = [];
  676.             $newFiltersOnlyNoChild = [];
  677.             foreach ($aFiltersOnlyNoChilds as $fVal) {
  678.                 $fRealId $fVal['oldCommand'] == 'getDesigner' $fVal['id'] : $fVal['oldId'];
  679.                 $realFilterProperty[$fVal['oldCommand']] [$fRealId] = $fVal;
  680.                 $realFilterProperty[$fVal['oldCommand']] [$fRealId] ['oldId'] = $fRealId;
  681.                 $realFilterProperty[$fVal['oldCommand']] [$fRealId] ['count'] = 0;
  682.                 $realFilterProperty[$fVal['oldCommand']] [$fRealId] ['coll_array'] = []; //добавляем массив колеккций дабы отсекать у родителей дубли
  683.                 $newFiltersOnlyNoChild[$fVal['id']] = $fVal;
  684.                 $newFiltersOnlyNoChild[$fVal['id']]['coll_array'] = [];
  685.             }
  686.         }
  687.         foreach ($rows as $row) {
  688.             if (!empty($row['attr_data']) && $attDate json_decode($row['attr_data'], true)) {
  689.                 //               удаляем интерфейсы
  690.                 unset($attDate['i_name']);
  691.                 unset($attDate['i_id']);
  692.                 unset($attDate['i_rating']);
  693.                 unset($attDate['i_monochrome']);
  694.                 unset($attDate['i_status']);
  695.                 unset($attDate['i_file']);
  696.                 unset($attDate['i_wall_and_floor']);
  697.                 unset($attDate['i_style']);
  698.                 unset($attDate['i_texture']);
  699.                 unset($attDate['fsi_x']);
  700.                 unset($attDate['fsi_y']);
  701.                 $row array_merge((array)$row$attDate); //удалить главный интерьер из сфинкса
  702.             }
  703.             if (!empty($row['c_exhibition']) && $exhibitionDate json_decode($row['c_exhibition'], true)) {
  704.                 $row['c_exhibition'] = $exhibitionDate;
  705.             } else {
  706.                 $row['c_exhibition'] = [];
  707.             }
  708.             if (!empty($row['c_awards']) && $c_awardsDate json_decode($row['c_awards'], true)) {
  709.                 $row['c_awards'] = $c_awardsDate;
  710.             } else {
  711.                 $row['c_awards'] = [];
  712.             }
  713.             if (!empty($row['c_designer_ids']) && $c_designer_idsDate json_decode($row['c_designer_ids'], true)) {
  714.                 $row['c_designer_ids'] = $c_designer_idsDate;
  715.             } else {
  716.                 $row['c_designer_ids'] = [];
  717.             }
  718.             // временно
  719.             if ($getCount) {
  720.                 if (empty($calculate[$row['coll']])) {
  721.                     //todo по факту эти поля нужно будет собрать из индекса который будет колеккцией пока у меня article2
  722.                     $calculate[$row['coll']] = [
  723.                         'getStyles' => [],
  724.                         'getSurfaces' => [],
  725.                         'getFacturas' => [],
  726.                         'getMaterials' => [],
  727.                         'getStone' => [],
  728.                         'getColors' => [],
  729.                         'shape' => [],
  730.                         'motive' => [],
  731.                         'motiv' => [],
  732. //                        'inside' => [],
  733.                         'discontinued' => [],
  734.                         'expressSample' => [],
  735.                         'getAwards' => [],
  736.                         'exhibition' => [],
  737.                         'size_x' => [],
  738.                         'size_y' => [],
  739.                         'tolsch' => [],
  740.                         'material' => [],
  741.                         'getTypeUsings' => [],
  742.                         'factory' => [],
  743.                         'bm' => [],
  744.                         'c_id' => [],
  745.                         'getThinGranite' => [],
  746.                         'size_big' => [],
  747.                         'getGlazedGranit' => [],
  748.                         'getThickGranite' => [],
  749.                         'searchPeriod' => [],
  750.                         'releaseYear' => [],
  751.                         'reviews' => [],
  752.                         'dyedInMass' => [],
  753.                         'colorBody' => [],
  754.                         'sliding' => [],
  755.                         'getUsings' => [],
  756.                         'getDesigner' => [],
  757.                         'monochrome' => [],
  758.                         'getPrcateg' => [],
  759.                         'getTypes' => [],
  760.                         'getCountry' => [],
  761.                         'a_price_cat_pln' => [],
  762.                         'getEdgeType' => [],
  763.                         'offShade' => [],
  764.                         'getCostCategory' => [],
  765.                     ];
  766.                 }
  767.                 //пробуем просто собрать данные;
  768.                 $calculate[$row['coll']]['getCostCategory'] = array_merge(
  769.                     $calculate[$row['coll']]['getCostCategory'],
  770.                     [$row[$priceFields[3]]]
  771.                 );
  772.                 $calculate[$row['coll']]['getStyles'] = array_merge(
  773.                     $calculate[$row['coll']]['getStyles'],
  774.                     explode(','$row['sid'])
  775.                 );
  776.                 $calculate[$row['coll']]['getSurfaces'] = array_merge(
  777.                     $calculate[$row['coll']]['getSurfaces'],
  778.                     explode(','$row['surface'])
  779.                 );
  780.                 $calculate[$row['coll']]['getMaterials'] = array_merge(
  781.                     $calculate[$row['coll']]['getMaterials'],
  782.                     explode(','$row['material'])
  783.                 );
  784.                 $calculate[$row['coll']]['getFacturas'] = array_merge(
  785.                     $calculate[$row['coll']]['getFacturas'],
  786.                     explode(','$row['a_texture'])
  787.                 );
  788.                 $calculate[$row['coll']]['getStone'] = array_merge(
  789.                     $calculate[$row['coll']]['getStone'],
  790.                     explode(','$row['a_stone_texture'])
  791.                 );
  792.                 $calculate[$row['coll']]['getColors'] = array_merge(
  793.                     $calculate[$row['coll']]['getColors'],
  794.                     explode(','$row['color'])
  795.                 );
  796.                 $calculate[$row['coll']]['shape'] = array_merge(
  797.                     $calculate[$row['coll']]['shape'],
  798.                     explode(','$row['shape'])
  799.                 );
  800.                 $calculate[$row['coll']]['motive'] = array_merge(
  801.                     $calculate[$row['coll']]['motive'],
  802.                     explode(','$row['a_motive'])
  803.                 );
  804.                 $calculate[$row['coll']]['motiv'] = array_merge(
  805.                     $calculate[$row['coll']]['motiv'],
  806.                     explode(','$row['a_motiv'])
  807.                 );
  808. //                $calculate[$row['coll']]['inside'] = array_merge(
  809. //                    $calculate[$row['coll']]['inside'],
  810. //                    [$row[$priceFields[0]]]
  811. //                );
  812.                 $calculate[$row['coll']]['discontinued'] = array_merge(
  813.                     $calculate[$row['coll']]['discontinued'],
  814.                     explode(','$row['typecoll'])
  815.                 );
  816.                 $calculate[$row['coll']]['expressSample'] = array_merge(
  817.                     $calculate[$row['coll']]['expressSample'],
  818.                     [$row['c_express_sample']]
  819.                 );
  820.                 $calculate[$row['coll']]['getAwards'] = array_merge(
  821.                     $calculate[$row['coll']]['getAwards'],
  822.                     [!empty($row['c_awards']) ? 2]
  823.                 );
  824.                 $calculate[$row['coll']]['exhibition'] = array_merge(
  825.                     $calculate[$row['coll']]['exhibition'],
  826.                     $row['c_exhibition']
  827.                 );
  828.                     $calculate[$row['coll']]['size_x'] = array_merge(
  829.                         $calculate[$row['coll']]['size_x'],
  830.                         [$row['size_x']]
  831.                     );
  832.                 $calculate[$row['coll']]['size_y'] = array_merge(
  833.                     $calculate[$row['coll']]['size_y'],
  834.                     [$row['size_y']]
  835.                 );
  836.                 $calculate[$row['coll']]['tolsch'] = array_merge(
  837.                     $calculate[$row['coll']]['tolsch'],
  838.                     [$row['tolsch']]
  839.                 );
  840.                 $calculate[$row['coll']]['material'] = array_merge(
  841.                     $calculate[$row['coll']]['material'],
  842.                     explode(','$row['material'])
  843.                 );
  844.                 $calculate[$row['coll']]['getTypeUsings'] = array_merge(
  845.                     $calculate[$row['coll']]['getTypeUsings'],
  846.                     explode(','$row['using'])
  847.                 );
  848.                 $calculate[$row['coll']]['factory'] = array_merge(
  849.                     $calculate[$row['coll']]['factory'],
  850.                     [$row['factory']]
  851.                 );
  852.                 $calculate[$row['coll']]['bm'] = array_merge($calculate[$row['coll']]['bm'], [$row['u_id']]);
  853.                 $calculate[$row['coll']]['c_id'] = array_merge($calculate[$row['coll']]['c_id'], [$row['c_id']]);
  854.                 $calculate[$row['coll']]['getThinGranite'] = array_merge(
  855.                     $calculate[$row['coll']]['getThinGranite'],
  856.                     [$row['thin_granite']]
  857.                 );
  858.                 $calculate[$row['coll']]['size_big'] = array_merge(
  859.                     $calculate[$row['coll']]['size_big'],
  860.                     [$row['size_big']]
  861.                 );
  862.                 $calculate[$row['coll']]['getGlazedGranit'] = array_merge(
  863.                     $calculate[$row['coll']]['getGlazedGranit'],
  864.                     [$row['glazed_granite']]
  865.                 );
  866.                 $calculate[$row['coll']]['getThickGranite'] = array_merge(
  867.                     $calculate[$row['coll']]['getThickGranite'],
  868.                     [$row['thick_granite']]
  869.                 );
  870.                 $calculate[$row['coll']]['searchPeriod'] = array_merge(
  871.                     $calculate[$row['coll']]['searchPeriod'],
  872.                     [$row['publish_period']]
  873.                 );
  874.                 $calculate[$row['coll']]['releaseYear'] = array_merge(
  875.                     $calculate[$row['coll']]['releaseYear'],
  876.                     [$row['c_release_year']]
  877.                 );
  878.                 $calculate[$row['coll']]['reviews'] = array_merge(
  879.                     $calculate[$row['coll']]['reviews'],
  880.                     explode(','$row['reviews'])
  881.                 );
  882.                 $calculate[$row['coll']]['dyedInMass'] = array_merge(
  883.                     $calculate[$row['coll']]['dyedInMass'],
  884.                     [$row['dyed_in_mass']]
  885.                 );
  886.                 $calculate[$row['coll']]['sliding'] = array_merge(
  887.                     $calculate[$row['coll']]['sliding'],
  888.                     [$row['sliding']]
  889.                 );
  890.                 $calculate[$row['coll']]['getUsings'] = array_merge(
  891.                     $calculate[$row['coll']]['getUsings'],
  892.                     explode(','$row['apply_id'])
  893.                 );
  894.                 $calculate[$row['coll']]['getDesigner'] = array_merge(
  895.                     $calculate[$row['coll']]['getDesigner'],
  896.                     $row['c_designer_ids']
  897.                 );
  898.                 $calculate[$row['coll']]['monochrome'] = array_merge(
  899.                     $calculate[$row['coll']]['monochrome'],
  900.                     explode(','$row['monochrome'])
  901.                 );
  902.                 $calculate[$row['coll']]['getPrcateg'] = array_merge(
  903.                     $calculate[$row['coll']]['getPrcateg'],
  904.                     [$row['pr_status']]
  905.                 );
  906.                 $calculate[$row['coll']]['getTypes'] = array_merge(
  907.                     $calculate[$row['coll']]['getTypes'],
  908.                     explode(','$row['type'])
  909.                 );
  910.                 $calculate[$row['coll']]['getCountry'] = array_merge(
  911.                     $calculate[$row['coll']]['getCountry'],
  912.                     [$row['country']]
  913.                 );
  914.                 $calculate[$row['coll']]['getEdgeType'] = array_merge(
  915.                     $calculate[$row['coll']]['getEdgeType'],
  916.                     explode(','$row['edge_type'])
  917.                 );
  918.                 $calculate[$row['coll']]['offShade'] = array_merge(
  919.                     $calculate[$row['coll']]['offShade'],
  920.                     [$row['off_shade']]
  921.                 );
  922.                 //
  923.                 //включаем если запрашивали
  924.             }
  925.             $row['apply_id'] = explode(','$row['apply_id']);
  926.             if (!empty($data['offset'])) {
  927.                 $num++;
  928.                 if ($data['offset'] > ($num 1)) {
  929.                     continue;
  930.                 }
  931.             }
  932.             if (!empty($row['c_accessible'])) {
  933.                 $noInteriorFactory true;
  934.             } else {
  935.                 $noInteriorFactory false;
  936.             }
  937.             if ($row['c_id'] == 3245628) {
  938.                 $row['c_name'] = App::trans('left_menu_glue');
  939.             }
  940.             //создаем клон из строки, но с данными из Коллекций для блатного удаления и фильтрации
  941.             //обратить внимание при поиске по коллекциям возврщает полный результат и потом фильтрует возможно можно что-то перенести в sphinx или в where
  942.             $iRows = [];
  943.             if (!empty($row['i'])) {
  944.                 // Заменяем значения $row значениями $row[i][n]
  945.                 foreach ($row['i'] as $v) {
  946.                     $iRows[] = array_merge($row$v);
  947.                 }
  948.             } else {
  949.                 //если нет, то для дальнейшей проверки оставим старое значение
  950.                 $iRows[] = $row;
  951.             }
  952.             foreach ($iRows as $intRow) {
  953.                 $row $intRow;
  954.                 if (
  955.                     !empty($data['searchFilter']['getUsings']) && count($data['searchFilter']) > &&
  956.                     !(count(array_intersect([$row['apply_id']], $data['searchFilter']['getUsings'])) > 0)
  957.                 ) {
  958.                     $applyShow false;
  959.                 } else {
  960.                     $applyShow true;
  961.                 }
  962.                 if ($row['process'] == 1) {
  963.                     $row['i_file'] = str_replace(['.jpeg''.jpg'], '.webp'$row['i_file']);
  964.                 }
  965.                 $noRestriction $this->getNoRestriction($data['searchFilter'], $row$oldTypeUsings ?? null);
  966.                 // есть ограничение на показ интерьером, но выбран фильтр применения, пропускаем такой элемент
  967.                 if (
  968.                     !empty($data['searchFilter']['getUsings'])
  969.                     && !$noRestriction
  970.                 ) {
  971.                     continue;
  972.                 }
  973.                 // базовая информация о коллекции
  974.                 if (empty($collections[$row['coll']])) {
  975.                     if ($row['c_status'] == 1) {
  976.                         $dataReview[$row['coll']] = [
  977.                             'name' => App::trans(
  978.                                 $row['c_header'] . '.short',
  979.                                 App::getCurLocale(),
  980.                                 [
  981.                                     '%collection%' => $row['c_name'],
  982.                                 ]
  983.                             ),
  984.                             'url' => App::generateUrl(
  985.                                 'app_collection',
  986.                                 [
  987.                                     'factoryUrl' => $row['f_url'],
  988.                                     'collectionUrl' => $row['c_url'],
  989.                                 ]
  990.                             ),
  991.                         ];
  992.                     }
  993.                     if (isset($data['searchFilter']['getTopMonth'])) {
  994.                         $arrow $row['c_pop30'] > $row['c_last_pop30'] ? 'up' 'down';
  995.                     } elseif (isset($data['searchFilter']['getTopWeek'])) {
  996.                         $arrow $row['c_pop7'] > $row['c_last_pop7'] ? 'up' 'down';
  997.                     } else {
  998.                         $arrow false;
  999.                     }
  1000.                     $collections[$row['coll']] = [
  1001.                         'c_id' => $row['c_id'],
  1002.                         'c_code' => $row['coll'],
  1003.                         'c_status' => $row['c_status'],
  1004.                         'c_name' => $row['c_name'],
  1005.                         'ratingMonth' => $row['rating_month'],
  1006.                         'arrow' => $arrow,
  1007.                         'c_header' => $row['c_header'],
  1008.                         'c_release_year' => $row['c_release_year'],
  1009.                         'c_url' => $row['c_url'],
  1010.                         'f_name' => $row['f_name'],
  1011.                         'f_url' => $row['f_id'] == 12 StrHelper::toLower($row['f_url']) : $row['f_url'],
  1012.                     ];
  1013.                     // если не пустое, то там массив с ID фильтров, иконки которых надо получить будет
  1014.                     $collections[$row['coll']]['c_awards'] = $row['c_awards'];
  1015.                     // если не пустое, то там массив с sub ID фильтров выставок
  1016.                     $collections[$row['coll']]['c_exhibition'] = $row['c_exhibition'];
  1017.                     $collections[$row['coll']]['date'] = date('d.m.Y'$row['publish_date']);
  1018.                     $collections[$row['coll']]['country'] = $row['country'];
  1019.                     $collections[$row['coll']]['country_code'] = $row['country_code'];
  1020.                     $collections[$row['coll']]['type'] = $row['type'];
  1021.                     $collections[$row['coll']]['material'] = $this->mapMaterial(
  1022.                         array_unique(explode(','$row['c_material'] ?? ''))
  1023.                     );
  1024.                     // вывел признак экспресс образца
  1025.                     $collections[$row['coll']]['hasExpressSample'] = !empty($row['c_express_sample']) && $row['c_express_sample'] == 1;
  1026.                     // добавил вывод prc_middle, что бы можно было проверить точность фильтрации
  1027.                     $prcCount = empty($row['prc_count']) ? null $row['prc_count'];
  1028.                     $prcVote = empty($row['prc_vote']) ? null $row['prc_vote'];
  1029.                     $prcMiddle 0;
  1030.                     if ($prcCount && $prcVote) {
  1031.                         $prcMiddle = ($prcVote $prcCount 0.01 $prcCount) * 100;
  1032.                     }
  1033.                     $collections[$row['coll']]['prc_count'] = $prcCount;
  1034.                     $collections[$row['coll']]['prc_vote'] = $prcVote;
  1035.                     $collections[$row['coll']]['prc_middle'] = $prcMiddle;
  1036.                     $collections[$row['coll']]['process'] = $row['process'] ?? 0;
  1037.                     $collections[$row['coll']]['alt'] = str_replace(
  1038.                         ['\\''"''\''],
  1039.                         '',
  1040.                         join(', ', [$row['f_name'], $row['c_name'], $row['i_name']])
  1041.                     );
  1042.                     $collections[$row['coll']]['author'] = empty($row['author']) ? null $row['author'];
  1043.                     $collections[$row['coll']]['sliding'] = empty($row['sliding']) ? [] : [$row['sliding']];
  1044.                     $collections[$row['coll']]['a_show'] = empty($data['searchFilter']['getUsings']) ? '1' '0';
  1045.                     // цены по умолчанию
  1046.                     $collections[$row['coll']]['price'] = (float)(max($row[$priceFields[0]], 1));
  1047.                     $collections[$row['coll']]['pr_min'] = (float)(max($row[$priceFields[2]], 1));
  1048.                     $collections[$row['coll']]['price_mq'] = (float)(max($row[$priceFields[1]], 1));
  1049.                     $collections[$row['coll']][$priceFields[4]] = (float)(max($row[$priceFields[4]], 1));
  1050.                     $collections[$row['coll']]['measureId'] = $row['measure'];
  1051.                     if (!empty($collections[$row['coll']]['price_mq']) && $row[$priceFields[3]] > 0) {
  1052.                         $collections[$row['coll']]['price'] = $collections[$row['coll']]['price_mq'];
  1053.                         $collections[$row['coll']]['measureId'] = 1;
  1054.                         $row['measure'] = 1;
  1055.                     }
  1056.                     $collections[$row['coll']]['measureText'] = $ed[$row['measure']] == 'm²' && LocaleHelper::getUserMeasure(
  1057.                     ) == 'ft' 'ft²' $ed[$row['measure']];
  1058.                     if (in_array($country, ['ch''no''hk''sg'])) {
  1059.                         $collections[$row['coll']]['price'] = round(
  1060.                             $collections[$row['coll']]['price'] - $collections[$row['coll']]['price'] * 18 118,
  1061.                             2
  1062.                         );
  1063.                         $collections[$row['coll']]['pr_min'] = round(
  1064.                             $collections[$row['coll']]['pr_min'] - $collections[$row['coll']]['pr_min'] * 18 118,
  1065.                             2
  1066.                         );
  1067.                         $collections[$row['coll']]['price_mq'] = round(
  1068.                             $collections[$row['coll']]['price_mq'] - $collections[$row['coll']]['price_mq'] * 18 118,
  1069.                             2
  1070.                         );
  1071.                     }
  1072.                     // для Гонконга конвертируем из мальтийских цен по курсу
  1073.                     if ($country == 'hk') {
  1074.                         $collections[$row['coll']]['price'] = CurrencyRateHelper::convertPrice(
  1075.                             'HKD',
  1076.                             $collections[$row['coll']]['price']
  1077.                         );
  1078.                         $collections[$row['coll']]['pr_min'] = CurrencyRateHelper::convertPrice(
  1079.                             'HKD',
  1080.                             $collections[$row['coll']]['pr_min']
  1081.                         );
  1082.                         $collections[$row['coll']]['price_mq'] = CurrencyRateHelper::convertPrice(
  1083.                             'HKD',
  1084.                             $collections[$row['coll']]['price_mq']
  1085.                         );
  1086.                         $collections[$row['coll']][$priceFields[4]] = CurrencyRateHelper::convertPrice(
  1087.                             'HKD',
  1088.                             $collections[$row['coll']][$priceFields[4]]
  1089.                         );
  1090.                     }
  1091.                     // для Сингапура конвертируем из мальтийских цен по курсу
  1092.                     if ($country == 'sg') {
  1093.                         $collections[$row['coll']]['price'] = CurrencyRateHelper::convertPrice(
  1094.                             'SGD',
  1095.                             $collections[$row['coll']]['price']
  1096.                         );
  1097.                         $collections[$row['coll']]['pr_min'] = CurrencyRateHelper::convertPrice(
  1098.                             'SGD',
  1099.                             $collections[$row['coll']]['pr_min']
  1100.                         );
  1101.                         $collections[$row['coll']]['price_mq'] = CurrencyRateHelper::convertPrice(
  1102.                             'SGD',
  1103.                             $collections[$row['coll']]['price_mq']
  1104.                         );
  1105.                         $collections[$row['coll']][$priceFields[4]] = CurrencyRateHelper::convertPrice(
  1106.                             'SGD',
  1107.                             $collections[$row['coll']][$priceFields[4]]
  1108.                         );
  1109.                     }
  1110.                     // убираем копейки
  1111.                     $collections[$row['coll']]['price'] = round($collections[$row['coll']]['price']);
  1112.                     $collections[$row['coll']]['pr_min'] = round($collections[$row['coll']]['pr_min']);
  1113.                     $collections[$row['coll']]['price_mq'] = round($collections[$row['coll']]['price_mq']);
  1114.                     // минимальная цена по коллекции если, не установлены дополнительные фильтры
  1115.                     if ($minTypeAll) {
  1116.                         $collections[$row['coll']]['pr_min'] = round($collections[$row['coll']][$priceFields[4]]);
  1117.                         $collections[$row['coll']]['price_mq'] = round($collections[$row['coll']]['pr_min']);
  1118.                         $collections[$row['coll']]['price'] = round($collections[$row['coll']]['pr_min']);
  1119.                     } elseif (empty($collections[$row['coll']]['price_mq'])) {
  1120.                         $collections[$row['coll']]['price_mq'] = round($collections[$row['coll']]['price']);
  1121.                     }
  1122.                     // собираем коды ед.изм.
  1123.                     $collections[$row['coll']]['measure'] = $ed[$row['measure']] ?? (App::trans(
  1124.                         $measure == 'm' 'measure_mq' 'measure_ft'
  1125.                     ));
  1126.                     $collections['i_names'][$row['coll']] = [];
  1127.                     $collections[$row['coll']]['interiors'] = [];
  1128.                     $collections[$row['coll']]['articles'][] = $this->article($row);
  1129.                     $collections[$row['coll']]['slidingShow'] = 0;
  1130.                     if (
  1131.                         !empty($data['searchFilter']['getSurfaces'])
  1132.                         && in_array(8$data['searchFilter']['getSurfaces'])
  1133.                     ) {
  1134.                         $collections[$row['coll']]['slidingShow'] = 1;
  1135.                     }
  1136.                     $collections['a_names'][$row['coll']][] = $row['a_name'];
  1137.                     if (
  1138.                         empty($data['searchFilter']['inside'])
  1139.                         && !$noInteriorFactory
  1140.                         && (empty($data['searchFilter'])
  1141.                             || count($data['searchFilter']) <= 2
  1142.                             && !empty($data['searchFilter']['getAlsoCollViewed'])
  1143.                             || count($data['searchFilter']) == 1
  1144.                             && (!empty($data['searchFilter']['factory'])
  1145.                                 || !empty($data['searchFilter'][''])
  1146.                             )
  1147.                         )
  1148.                         && !empty($row['is_main'])
  1149.                     ) {               // специальная заглушка для главной картинки коллекции на случай если не выбраны фильтры
  1150.                         [
  1151.                             $mainInteriorId,
  1152.                             $mainInteriorName,
  1153.                             $mainInteriorFile,
  1154.                             $fileSizeX,
  1155.                             $fileSizeY,
  1156.                             $iRating,
  1157.                         ] = explode('|'$row['is_main']);
  1158.                         if (!$fileSizeY == && !empty($mainInteriorName)) {
  1159.                             $iName $mainInteriorName;
  1160.                             $iFile $mainInteriorFile;
  1161.                             if ($row['a_head'] || !empty($data['searchFilter']['factory'])) {
  1162.                                 $collections['i_names'][$row['coll']][] = $iName;
  1163.                                 $collections[$row['coll']]['interiors'][] = [
  1164.                                     'i_id' => $mainInteriorId,
  1165.                                     'i_name' => $iName,
  1166.                                     'i_file' => $iFile,
  1167.                                     'i_rating' => $iRating,
  1168.                                     'x' => $fileSizeX,
  1169.                                     'y' => $fileSizeY,
  1170.                                 ];
  1171.                             }
  1172.                         }
  1173.                     }
  1174.                     if (
  1175.                         !$noInteriorFactory
  1176.                         && !empty($row['i_name'])
  1177.                         && isset($row['i_id']) && $row['i_id'] !== null
  1178.                         && $noRestriction
  1179.                         && $applyShow
  1180.                         && !in_array($row['i_name'], $collections['i_names'][$row['coll']])
  1181.                         && (empty($data['searchFilter']['getUsings'])
  1182.                             || in_array(8$data['searchFilter']['getUsings'])
  1183.                             && $row['apply_id'] == 8
  1184.                             || !in_array(8$data['searchFilter']['getUsings'])
  1185.                         )
  1186.                     ) {
  1187.                         $iName $row['i_name'];
  1188.                         $iFile $row['i_file'];
  1189.                         if ($row['a_head']) {
  1190.                             $collections['i_names'][$row['coll']][] = $iName;
  1191.                             $collections[$row['coll']]['interiors'][] = [
  1192.                                 'i_id' => $row['i_id'],
  1193.                                 'i_name' => $iName,
  1194.                                 'i_file' => $iFile,
  1195.                                 'x' => $row['fsi_x'],
  1196.                                 'y' => $row['fsi_y'],
  1197.                                 'i_rating' => $row['i_rating'],
  1198.                             ];
  1199.                         }
  1200.                     }
  1201.                 } else {
  1202.                     // если запрошена фильтрация по коллекции, то выводим все артикулы
  1203.                     if (!empty($_GET['debug']) || !empty($data['searchFilter']['inside'])) {
  1204.                         $collections[$row['coll']]['articles'][] = $this->article($row);
  1205.                     }
  1206.                     if (
  1207.                         !empty($row['author']) &&
  1208.                         is_array($collections[$row['coll']]['author']) &&
  1209.                         !in_array($row['author'], $collections[$row['coll']]['author'])
  1210.                     ) {
  1211.                         $collections[$row['coll']]['author'] = $row['author'];
  1212.                     }
  1213.                     if (!empty($row['sliding']) && !in_array($row['sliding'], $collections[$row['coll']]['sliding'])) {
  1214.                         $collections[$row['coll']]['sliding'][] = $row['sliding'];
  1215.                     }
  1216.                     // собираем коды ед.изм.
  1217.                     $collections[$row['coll']]['measure'] = $ed[$row['measure']] ?? (App::trans(
  1218.                         $measure == 'm' 'measure_mq' 'measure_ft'
  1219.                     ));
  1220.                     // если не установлен лимит или интерьера нет для вывода, то смотрим артикулы
  1221.                     if (
  1222.                         !empty($_GET['debug'])
  1223.                         || $limit == 0
  1224.                         || count($collections[$row['coll']]['interiors']) < $limit
  1225.                     ) {
  1226.                         if (
  1227.                             (!empty($data['searchFilter']['getPrcateg'])
  1228.                                 && (in_array(7$data['searchFilter']['getPrcateg'])
  1229.                                     || in_array(6$data['searchFilter']['getPrcateg'])
  1230.                                 )
  1231.                             )
  1232.                             || !empty($data['searchFilter']['coll']) || count(
  1233.                                 $collections[$row['coll']]['articles']
  1234.                             ) == 0
  1235.                         ) {
  1236.                             /** см. выше для первого вхождения артикула в коллекцию */
  1237.                             if (
  1238.                                 empty($data['searchFilter']['getStyles'])
  1239.                                 || (!empty($data['searchFilter']['getStyles'])
  1240.                                     && in_array($row['a_style'], $data['searchFilter']['getStyles'])
  1241.                                 )
  1242.                             ) {
  1243.                                 if (!in_array($row['a_name'], $collections['a_names'][$row['coll']])) {
  1244.                                     $collections[$row['coll']]['articles'][] = $this->article($row);
  1245.                                 }
  1246.                             }
  1247.                         }
  1248.                         if (
  1249.                             !$noInteriorFactory
  1250.                             && !empty($row['i_name'])
  1251.                             && isset($row['i_id']) && $row['i_id'] !== null
  1252.                             && $noRestriction
  1253.                             && $applyShow
  1254.                             && !in_array($row['i_name'], $collections['i_names'][$row['coll']])
  1255.                             && (
  1256.                                 empty($data['searchFilter']['getUsings'])
  1257.                                 || !in_array(8$data['searchFilter']['getUsings'])
  1258.                                 || $row['apply_id'] == 8
  1259.                             )
  1260.                         ) {
  1261.                             if ($row['a_head']) {
  1262.                                 $collections['i_names'][$row['coll']][] = $row['i_name'];
  1263.                                 $collections[$row['coll']]['interiors'][] = [
  1264.                                     'i_id' => $row['i_id'],
  1265.                                     'i_name' => $row['i_name'],
  1266.                                     'i_file' => $row['i_file'],
  1267.                                     'x' => $row['fsi_x'],
  1268.                                     'y' => $row['fsi_y'],
  1269.                                     'i_rating' => $row['i_rating'],
  1270.                                 ];
  1271.                             }
  1272.                         }
  1273.                     }
  1274.                     $collections['a_names'][$row['coll']][] = $row['a_name'];
  1275.                 }
  1276.             }
  1277.         }
  1278.         unset($collections['i_names']);
  1279.         unset($collections['a_names']);
  1280.         // проверяем и фильтруем дополнительно выставки
  1281.         if (!empty($data['searchFilter']['exhibition'])) {
  1282.             $idExh $data['searchFilter']['exhibition'];
  1283.             foreach ($collections as $i_ => $coll_) {
  1284.                 if (!array_intersect($idExh$coll_['c_exhibition'])) {
  1285.                     unset($collections[$i_]);
  1286.                 }
  1287.             }
  1288.         }
  1289.         if (
  1290.             !empty($data['searchFilter']['getPrcateg'])
  1291.             && (in_array(6$data['searchFilter']['getPrcateg'])
  1292.                 || in_array(7$data['searchFilter']['getPrcateg'])
  1293.             )
  1294.         ) {
  1295.             $collections $this->setIndexesForArticlesInCollections($collections);
  1296.         }
  1297.         if ($getCount) {
  1298.             //Отсекаем ненужные колекции
  1299.             foreach ($calculate as $i => $coll) {
  1300.                 if (!isset($collections[$i])) {
  1301.                     unset($calculate[$i]);
  1302.                 }
  1303.             }
  1304.         }
  1305.         $collections array_values($collections);
  1306.         if ($getCount) {
  1307.             $fixfilter $this->getCount($calculate$realFilterProperty$newFiltersOnlyNoChild);
  1308.             if (!empty($fixfilter)) {
  1309.                 $res_enabledSize $fixfilter;
  1310.             } else {
  1311.                 $res_enabledSize = [];
  1312.             }
  1313.             $collections = [
  1314.                 'collections' => $collections,
  1315.                 'calculate' => $res_enabledSize,
  1316.             ];
  1317.         }
  1318.         if ($full) {
  1319.             return [
  1320.                 'res' => $collections,
  1321.                 'codes' => $dataReview,
  1322.             ];
  1323.         }
  1324.         return $collections;
  1325.     }
  1326.     /**
  1327.      * Подсчитывает Коллекции в свойстве
  1328.      * @param array $calculate - Собраные значения
  1329.      * @param array $realFilterProperty - фильтр связь ключей старые новые
  1330.      * @return array - подсчет коллекций
  1331.      * @throws Exception
  1332.      */
  1333.     private function getCount(array $calculate, array $realFilterProperty = [], $aFiltersOnlyNoChilds = []): array
  1334.     {
  1335.         $oldId 'id';
  1336.         $res = [];
  1337.         //перебераем массив с коллекциями не товарами
  1338.         foreach ($calculate as $coll => $values) {
  1339.             //перебираем их свойства
  1340.             foreach ($values as $key => $value) {
  1341.                 //перебираем их значение
  1342.                 foreach (array_unique($value) as $v) {
  1343.                     //тут вся логика с фильтром
  1344.                     if (isset($realFilterProperty[$key][$v])) {
  1345.                         // $realFilterProperty[$key][$v]['count']++;
  1346.                         if (isset($res[$key][$realFilterProperty[$key][$v][$oldId]])) {
  1347.                             $res[$key][$realFilterProperty[$key][$v][$oldId]]++;
  1348.                         } else {
  1349.                             $res[$key][$realFilterProperty[$key][$v][$oldId]] = 1;
  1350.                         }
  1351.                     } else {
  1352.                         //если такого фильтра не существует нужно создать и присвоить его свойству первое вхождение
  1353.                         if (isset($res[$key][$v])) {
  1354.                             $res[$key][$v]++;
  1355.                         } else {
  1356.                             $res[$key][$v] = 1;
  1357.                         }
  1358.                     }
  1359.                 }
  1360.             }
  1361.         }
  1362.         return $res;
  1363.     }
  1364.     /**
  1365.      * @param $row
  1366.      * @return array
  1367.      * @throws Exception
  1368.      */
  1369.     private function article($row): array
  1370.     {
  1371.         // сохраняем id артикула для выборки подробных данных артикулов подходящих под отбор
  1372.         $this->articlesId[] = $row['a_id'];
  1373.         return [
  1374.             'a_id' => $row['a_id'],
  1375.             'a_name' => $row['a_name'],
  1376.             'file' => $row['process'] == str_replace(['.jpeg''.jpg'], '.webp'$row['file']) : $row['file'],
  1377.             'a_x' => $row['fs_x'],
  1378.             'a_y' => $row['fs_y'],
  1379.             'b_g' => $row['border_grey'],
  1380.             'alt' => str_replace(['\\''"''\''], ''join(', ', [$row['f_name'], $row['c_name'], $row['a_name']])),
  1381.         ];
  1382.     }
  1383.     /**
  1384.      * @throws Exception
  1385.      */
  1386.     private function mapMaterial(array $collectionMaterials = []): array
  1387.     {
  1388.         $listMaterialCollection = [];
  1389.         foreach ($collectionMaterials as $materialId) {
  1390.             if (!empty($this->getMaterials()[$materialId])) {
  1391.                 $listMaterialCollection[] = $this->getMaterials()[$materialId];
  1392.             }
  1393.         }
  1394.         return $listMaterialCollection;
  1395.     }
  1396.     /**
  1397.      * @return array
  1398.      * @throws Exception
  1399.      */
  1400.     private function getMaterials(): array
  1401.     {
  1402.         if (count($this->materials) == 0) {
  1403.             /** @var ListMaterialRepository $repoMaterialList */
  1404.             $repoMaterialList App::getRepository(ListMaterial::class);
  1405.             $list $repoMaterialList->getList(true);
  1406.             /** @var ListMaterial $r */
  1407.             foreach ($list as $r) {
  1408.                 $materials App::trans('coll_preview_' $r['alias']);
  1409.                 $position strpos($materials'_');
  1410.                 if ($position !== false) {
  1411.                     $materials App::trans($r['alias']);
  1412.                 }
  1413.                 $this->materials[$r['id']] = $materials;
  1414.             }
  1415.         }
  1416.         return $this->materials;
  1417.     }
  1418.     private function getPriceFields(string $currencystring $countrystring $measure): array
  1419.     {
  1420.         if ($currency === 'EUR') {
  1421.             switch ($country) {
  1422.                 case 'de':
  1423.                     return ['price_euro_de''price_mq_euro_de''pr_min_euro_de''a_price_cat_de''price_sort_de'];
  1424.                 case 'at':
  1425.                     return ['price_euro_at''price_mq_euro_at''pr_min_euro_at''a_price_cat_at''price_sort_at'];
  1426.                 case 'fi':
  1427.                     return ['price_euro_fi''price_mq_euro_fi''pr_min_euro_fi''a_price_cat_fi''price_sort_fi'];
  1428.                 case 'fr':
  1429.                     return ['price_euro_fr''price_mq_euro_fr''pr_min_euro_fr''a_price_cat_fr''price_sort_fr'];
  1430.                 case 'it':
  1431.                     return ['price_euro_it''price_mq_euro_it''pr_min_euro_it''a_price_cat_it''price_sort_it'];
  1432.                 case 'be':
  1433.                     return ['price_euro_be''price_mq_euro_be''pr_min_euro_be''a_price_cat_be''price_sort_be'];
  1434.                 case 'ie':
  1435.                     return ['price_euro_ie''price_mq_euro_ie''pr_min_euro_ie''a_price_cat_ie''price_sort_ie'];
  1436.                 case 'nl':
  1437.                     return ['price_euro_nl''price_mq_euro_nl''pr_min_euro_nl''a_price_cat_nl''price_sort_nl'];
  1438.                 case 'es':
  1439.                     return ['price_euro_es''price_mq_euro_es''pr_min_euro_es''a_price_cat_es''price_sort_es'];
  1440.                 case 'ru':
  1441.                     return ['price_rue''price_mq_rue''pr_min_rue''a_price_cat_rue''price_sort_rub'];
  1442.                 case 'gb':
  1443.                     return ['price_gbe''price_mq_gbe''pr_min_gbe''a_price_cat_gbe''price_sort_gbp'];
  1444.                 case 'ch':
  1445.                     return ['price_che''price_mq_che''pr_min_che''a_price_cat_che''price_sort_chf'];
  1446.                 case 'se':
  1447.                     return ['price_see''price_mq_see''pr_min_see''a_price_cat_see''price_sort_sek'];
  1448.                 case 'pl':
  1449.                     return ['price_ple''price_mq_ple''pr_min_ple''a_price_cat_ple''price_sort_pln'];
  1450.                 case 'us':
  1451.                     if ($measure === 'ft') {
  1452.                         return [
  1453.                             'price_fq_use',
  1454.                             'price_fq_use',
  1455.                             'pr_min_f_use',
  1456.                             'a_price_cat_fq_use',
  1457.                             'price_sort_fq_usd'
  1458.                         ];
  1459.                     }
  1460.                     return ['price_use''price_mq_use''pr_min_use''a_price_cat_use''price_sort_usd'];
  1461.                 case 'ca':
  1462.                     if ($measure === 'ft') {
  1463.                         return ['price_cae''price_fq_cae''pr_min_cae''a_price_cat_fq_cae''price_sort_fq_cad'];
  1464.                     }
  1465.                     return ['price_cae''price_mq_cae''pr_min_cae''a_price_cat_cae''price_sort_cad'];
  1466.             }
  1467.             return ['price_euro''price_mq_euro''pr_min_euro''a_price_cat''price_sort'];
  1468.         }
  1469.         if ($country === 'ru' && $currency === 'RUB') {
  1470.             return ['price_rub''price_mq_rub''pr_min_rub''a_price_cat_rub''price_sort_rub'];
  1471.         }
  1472.         if ($country === 'gb' && $currency === 'GBP') {
  1473.             return ['price_gbp''price_mq_gbp''pr_min_gbp''a_price_cat_gbp''price_sort_gbp'];
  1474.         }
  1475.         if ($country === 'ch' && $currency === 'CHF') {
  1476.             return ['price_chf''price_mq_chf''pr_min_chf''a_price_cat_chf''price_sort_chf'];
  1477.         }
  1478.         if ($country === 'se' && $currency === 'SEK') {
  1479.             return ['price_sek''price_mq_sek''pr_min_sek''a_price_cat_sek''price_sort_sek'];
  1480.         }
  1481.         if ($country === 'dk' && $currency === 'DKK') {
  1482.             return ['price_dkk''price_mq_dkk''pr_min_dkk''a_price_cat_dkk''price_sort_dkk'];
  1483.         }
  1484.         if ($country === 'no' && $currency === 'NOK') {
  1485.             return ['price_nok''price_mq_nok''pr_min_nok''a_price_cat_nok''price_sort_nok'];
  1486.         }
  1487.         if ($country === 'pl' && $currency === 'PLN') {
  1488.             return ['price_pln''price_mq_pln''pr_min_pln''a_price_cat_pln''price_sort_pln'];
  1489.         }
  1490.         if ($country === 'us' && $currency === 'USD') {
  1491.             if ($measure === 'ft') {
  1492.                 return ['price_fq_usd''price_fq_usd''pr_min_f_usd''a_price_cat_fq_usd''price_sort_fq_usd'];
  1493.             }
  1494.             return ['price_usd''price_mq_usd''pr_min_usd''a_price_cat_usd''price_sort_usd'];
  1495.         }
  1496.         if ($country === 'ca' && $currency === 'CAD') {
  1497.             if ($measure === 'ft') {
  1498.                 return ['price_cad''price_fq_cad''pr_min_cad''a_price_cat_fq_cad''price_sort_fq_cad'];
  1499.             }
  1500.             return ['price_cad''price_mq_cad''pr_min_cad''a_price_cat_cad''price_sort_cad'];
  1501.         }
  1502.         return ['price_euro''price_mq_euro''pr_min_euro''a_price_cat''price_sort'];
  1503.     }
  1504.     /**
  1505.      * Ограничение на показ интерьеров
  1506.      *
  1507.      * @param array $searchFilter
  1508.      * @param array $row
  1509.      * @param array|null $oldTypeUsings
  1510.      * @return bool
  1511.      */
  1512.     private function getNoRestriction(array $searchFilter, array $row, ?array $oldTypeUsings): bool
  1513.     {
  1514.         $iTexture explode(','$row['i_texture']);
  1515.         // В этой просьбе попросили исключить из ограничения фактуру по 17 кодом https://te.remote.team/#/discus/F4D2CA8B-BE66-7853-8FDC-2CFE011A151C/
  1516.         $iTexture[] = 17;
  1517.         //если поиск по группе и интерьер содержит текстуру подгруппы, то выведем как-бу-то это интерьер группы
  1518.         if (
  1519.             !empty($searchFilter['getFacturas'])
  1520.             && in_array(999$searchFilter['getFacturas'])
  1521.             && in_array($iTexture$this->subFilters)
  1522.         ) {
  1523.             $iTexture[] = 999;
  1524.         }
  1525.         //внутри коллекции для интерьеров надо проверить, что привязаны заглавный артикулы
  1526.         if (!empty($searchFilter['inside']) && empty($row['a_head'])) {
  1527.             return true;
  1528.         }
  1529.         // ограничение на показ интерьера по признаку назначение
  1530.         if (
  1531.             !empty($oldTypeUsings)
  1532.             && (array_search(4$oldTypeUsings)
  1533.                 && !$row['i_wall_and_floor']
  1534.                 || !in_array($row['i_type'], $oldTypeUsings)
  1535.             )
  1536.         ) {
  1537.             return false;
  1538.         }
  1539.         // ограничение на показ интерьера по признаку стиль
  1540.         // внутри коллекции не используется это условие !!!!уже используется https://te2.remote.team/discus/C0B5DD6C-8487-9233-5238-08E2AF112A60?goto=true
  1541.         // так же это ограничение не должно работать если стиль "ручная работа"
  1542.         if (
  1543.             isset($row['i_style'])
  1544.             && $row['i_style'] == 0
  1545.             && !empty($searchFilter['getStyles'])
  1546.             && !in_array(14$searchFilter['getStyles'])
  1547.             && !in_array(14, [$row['a_style'], $row['styleida']])
  1548.         ) {
  1549.             return false;
  1550.         }
  1551.         // если выбран фильтр монохром надо проверить, есть ли он у интерьера
  1552.         if (
  1553.             !empty($searchFilter['getColors'])
  1554.             && in_array(99$searchFilter['getColors'])
  1555.             && !in_array(99$iTexture)
  1556.         ) {
  1557.             return false;
  1558.         }
  1559.         // ограничение на показ интерьеров при поиске по фактуре
  1560.         if (
  1561.             (
  1562.                 (empty($searchFilter['getTypes'])
  1563.                     || !in_array($row['type'], $searchFilter['getTypes'])
  1564.                 )
  1565.                 && (empty($searchFilter['getMaterials'])
  1566.                     || !in_array(99$searchFilter['getMaterials'])
  1567.                     || $row['material'] != 99
  1568.                 )
  1569.             )
  1570.             && empty($searchFilter['inside'])
  1571.         ) {
  1572.             if (
  1573.                 !empty($searchFilter['getFacturas'])
  1574.                 && count(array_intersect($iTexture$searchFilter['getFacturas'])) == 0
  1575.             ) {
  1576.                 return true;
  1577.             }
  1578.             if (
  1579.                 !empty($searchFilter)
  1580.                 && (!empty($searchFilter['getColors'])
  1581.                     || !empty($searchFilter['getMaterials'])
  1582.                     || !empty($searchFilter['getSurfaces'])
  1583.                 )
  1584.                 && empty($row['type_filter'])
  1585.             ) { // ограничение подбора интерьеров по некоторым фильтрам
  1586.                 return false;
  1587.             }
  1588.             return true;
  1589.         }
  1590.         if (empty($searchFilter['getFacturas'])) {
  1591.             return true;
  1592.         }
  1593.         if (count(array_intersect($iTexture$searchFilter['getFacturas'])) > 0) {
  1594.             return true;
  1595.         }
  1596.         return false;
  1597.     }
  1598.     /**
  1599.      * @param array $collections
  1600.      * @return array
  1601.      */
  1602.     private function setIndexesForArticlesInCollections(array $collections): array
  1603.     {
  1604.         $n 0// для простановки индексов артикулов
  1605.         foreach ($collections as &$collection) {
  1606.             unset($collection['interiors']);
  1607.             if (!empty($collection['articles'])) {
  1608.                 foreach ($collection['articles'] as &$item) {
  1609.                     $item['num'] = $n;
  1610.                     $n++;
  1611.                 }
  1612.             }
  1613.         }
  1614.         return $collections;
  1615.     }
  1616.     //нужно узнать не сортирует ли человек случайно чтобы отсортировать за него
  1617.     /**
  1618.      * @return int
  1619.      * @throws Exception
  1620.      */
  1621.     public function getSearchSortId()
  1622.     {
  1623.         $sort App::getSession()->get('sort_catalog_tmp');
  1624.         if ($sort == null) {
  1625.             $sort App::getRequest()->get('sort');
  1626.         }
  1627.         if ($sort == null) {
  1628.             $sort App::getRequest()->cookies->get('sort_catalog');
  1629.         }
  1630.         if ($sort == null) {
  1631.             $sort 0;
  1632.         }
  1633.         return $sort;
  1634.     }
  1635. }