src/WebBundle/Controller/CatalogController.php line 46

Open in your IDE?
  1. <?php
  2. namespace WebBundle\Controller;
  3. use Exception;
  4. use FlexApp\DTO\RequestCatalogDTO;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. use WebBundle\Helper\App;
  10. use WebBundle\Helper\FilterHelper;
  11. use WebBundle\Helper\HideFactoryCountriesHelper;
  12. use WebBundle\Helper\RequestHelper;
  13. use WebBundle\Helper\SearchLogHelper;
  14. use WebBundle\Helper\StatsHelper;
  15. use WebBundle\Repository\CollectionRepository;
  16. use WebBundle\Repository\FactoryRepository;
  17. use WebBundle\Repository\FilterRepository;
  18. use WebBundle\Repository\PublicationRepository;
  19. use WebBundle\Service\ReviewsService;
  20. use WebBundle\Service\SearchService;
  21. use WebBundle\Service\SphinxSearcherService;
  22. use WebBundle\Service\VisitedService;
  23. class CatalogController extends ExtendedController
  24. {
  25.     /** @required */
  26.     public PublicationRepository $publicationRepository;
  27.     /** @required */
  28.     public FilterRepository $filterRepository;
  29.     /** @required */
  30.     public CollectionRepository $collectionRepository;
  31.     /** @required */
  32.     public FactoryRepository $factoryRepository;
  33.     /** @required */
  34.     public VisitedService $visitedService;
  35.     /** @required */
  36.     public SphinxSearcherService $sphinxSearcherService;
  37.     /** @required */
  38.     public ReviewsService $reviewsService;
  39.     /** @required */
  40.     public SearchService $searchService;
  41.     public function indexAction(Request $request, ?string $key null$subkey null): Response
  42.     {
  43.         ini_set('memory_limit''2048M');
  44.         $reqCatDTO = new RequestCatalogDTO($request$key$subkey);
  45.         $oSSearch $this->searchService->setFilter($reqCatDTO);
  46.         //  перенаправляем на верную страницу каталога
  47.         if ($oSSearch->isRedirect()) {
  48.             return $oSSearch->getRedirect();
  49.         }
  50.         if ($oSSearch->filterService()->isTestingBrand()) {
  51.             if (!App::isRole('ROLE_TEST')) {
  52.                 throw new NotFoundHttpException('factory not found');
  53.             }
  54.         }
  55.         $dataFilterSearch $oSSearch->getSearchKey() ? $oSSearch->getReplaceParentWithChildren() : [];
  56.         $subkey $oSSearch->getSearchSubKey();
  57.         // $oSSearch->setGCount(true); //Тогда будет считать
  58.         $result $oSSearch->getResult();
  59.         $calculate $oSSearch->getCalculate();
  60.         $limit $oSSearch->getLimit();
  61.         $pageCount intval(ceil($result['count'] / ($limit ?: 1)));
  62.         $linkSamples null;
  63.         if ($oSSearch->isPageExpressSample()) {
  64.             $linkSamples $this->publicationRepository->getUrlBlogExpressSamples();
  65.         }
  66.         $factory null;
  67.         if ($oSSearch->filterService() && $oSSearch->filterService()->getCurBrand()) {
  68.             $factoryId $oSSearch->filterService()->getCurBrand()->getId();
  69.             $factory $this->factoryRepository->find($factoryId);
  70.         }
  71.         $factoryReviewsUrl $factory $this->generateUrl('factory_reviews', ['id' => $factory->getId()]) : "";
  72.         $avgReviewsStar 0;
  73.         if ($factory) {
  74.             $reviews $this->reviewsService->getReviewsByFactory($factory);
  75.             $sum 0;
  76.             $count 0;
  77.             foreach ($reviews as $collection) {
  78.                 foreach ($collection['reviews'] as $review) {
  79.                     $sum += $review['star'];
  80.                     $count++;
  81.                 }
  82.             }
  83.             if ($count 0) {
  84.                 $avgReviewsStar round($sum $count2);
  85.             }
  86.         }
  87.         $output = [
  88.             'content' => [
  89.                 'h1' => $oSSearch->getTitleHtml(),
  90.                 'html' => $oSSearch->getHtml(),
  91.                 'amount' => $oSSearch->getAmount(),
  92.                 'key' => $key,
  93.                 'subkey' => $subkey,
  94.                 'fullKey' => $key $subkey "/$subkey'',
  95.                 'brand' => $oSSearch->filterService()->getCurBrand(),
  96.                 'isDesigner' => $oSSearch->isDesignerStyle(),
  97.             ],
  98.             'meta' => [
  99.                 'title' => $oSSearch->getMetaManager()->getTitle(),
  100.                 'description' => $oSSearch->getMetaManager()->getDescription(),
  101.                 'keywords' => $oSSearch->getMetaManager()->getKeywords(),
  102.             ],
  103.             'result' => $result,
  104.             'activeFilters' => $oSSearch->getFiltersGTM(),
  105.             'page' => $oSSearch->getPage(),
  106.             'pageCount' => $pageCount,
  107.             'limit' => $limit,
  108.             'sortId' => $oSSearch->getSearchSortId(),
  109.             'sortList' => $oSSearch->getSortList(),
  110.             'discount' => $oSSearch->getDiscount(),
  111.             'top20' => $oSSearch->getTop20(),
  112.             'dataFilterSearch' => json_encode($dataFilterSearch),
  113.             'gclid' => $request->query->get('gclid'null),
  114.             'noindex' => $oSSearch->isNoindex(),
  115.             'isPageReleaseYear' => $oSSearch->isPageReleaseYear(),
  116.             'isPageExhibition' => $oSSearch->isPageExhibition(),
  117.             'linkSamples' => $linkSamples,
  118.             'factoryReviewsUrl' => $factoryReviewsUrl,
  119.         ];
  120.         $output['calculate'] = $calculate ?? []; //попытка передать в твиг
  121.         if ($oSSearch->filterService() && $oSSearch->filterService()->getCurBrand()) {
  122.             $factoryId $oSSearch->filterService()->getCurBrand()->getId();
  123.             $factory $this->factoryRepository->find($factoryId);
  124.             $collections $this->reviewsService->getReviewsByFactory($factory);
  125.             $reviewsTotalCount 0;
  126.             foreach ($collections as $c) {
  127.                 $reviewsTotalCount += count($c['reviews']);
  128.             }
  129.             $output['result']['reviewsTotalCount'] = $reviewsTotalCount;
  130.             $output['result']['avgReviewsStar'] = $avgReviewsStar;
  131.             // $output['result']['factoryReviews'] = $factory ? $this->reviewsService->getReviewsByFactory($factory) : null;
  132.         }
  133.         StatsHelper::addHits($oSSearch->filterService());
  134.         SearchLogHelper::save(['url' => App::getRequest()->getUri(), 'title' => $oSSearch->getMetaManager()->getTitle()]);
  135.         $output['noFloor'] = true;
  136.         $keyUrl FilterHelper::checkPageUrl('recently-added-tiles');
  137.         $topWeek FilterHelper::checkPageUrl('top-week');
  138.         $topMonth FilterHelper::checkPageUrl('top-month');
  139.         //        if ($key == $topWeek || $key == $topMonth || ($key != null && $keyUrl == $key)) {
  140.         //            unset($output['result']['fReview']);
  141.         //        }
  142.         unset($output['result']['fReview']);
  143.         //        http://te.loc/ru/catalogue/novogres?debug=1
  144.         // переадресация на каталог с сообщением если сняли фабрику
  145.         // https://te.remote.team/#/discus/98061423-1D64-57EB-547F-90E7AD5E8305/
  146.         // убрали переaдресацию, теперь просто показываем сообщение и скрываем результаты показа
  147.         if (
  148.             $oSSearch->isBrands()
  149.             && $oSSearch->isOneFilter()
  150.             && (
  151.                 $oSSearch->filterService()->getCurBrand()->getStatus() == 2
  152.                 || in_array($oSSearch->filterService()->getCurBrand()->getId(), HideFactoryCountriesHelper::codes())
  153.             )
  154.         ) {
  155.             $output['fMsg'] = [
  156.                 'name' => $oSSearch->filterService()->getCurBrand()->getName(),
  157.                 'url' => $this->generateUrl('app_catalog'),
  158.             ];
  159.         } else {
  160.             // принято решение страницу дизайнера, который не имеет активных коллекций переадресовывать на список дизайнеров
  161.             if ($oSSearch->isOneFilter() && $oSSearch->isDesigner() && $oSSearch->getResult()['count'] == 0) {
  162.                 $keyUrl FilterHelper::checkPageUrl('designer');
  163.                 $msg trim(str_replace('edit'''html_entity_decode(strip_tags($oSSearch->getTitleHtml()))));
  164.                 $output['msg'] = [
  165.                     'name' => $msg,
  166.                     'url' => $this->generateUrl('app_catalog', ['key' => $keyUrl]),
  167.                 ];
  168.             }
  169.         }
  170.         $this->visitedService->addHistory($oSSearch);
  171.         if (RequestHelper::isAjax()) {
  172.             if ($oSSearch->getPage() == and !$reqCatDTO->isOnlyPage()) {
  173.                 $response = new JsonResponse(
  174.                     [
  175.                         'content' => $this->render('@Web/Catalog/search-content.html.twig'$output)->getContent(),
  176.                         'key' => $oSSearch->getSearchKey(),
  177.                         'url' => urldecode($this->generateUrl(
  178.                             'app_catalog',
  179.                             ['key' => $oSSearch->getSearchKey(), 'subkey' => $subkey]
  180.                         )),
  181.                         'dataFilterSearch' => $dataFilterSearch,
  182.                         'title' => $oSSearch->getMetaManager()->getTitle(),
  183.                         'isDesigner' => $oSSearch->isDesignerStyle(),
  184.                         'isPageReleaseYear' => $oSSearch->isPageReleaseYear(),
  185.                         'isPageExhibition' => $oSSearch->isPageExhibition(),
  186.                         'page' => $oSSearch->getPage(),
  187.                         'pageCount' => $pageCount,
  188.                         'limit' => $limit,
  189.                         'count' => $result['count'],
  190.                         'calculate' => $calculate,
  191.                         'history' => [
  192.                             'all' => $this->visitedService->getCountHistory(),
  193.                             'list' => $this->render('@Web/Visit/last.html.twig', ['visited' => $this->visitedService->getLastHistory()])->getContent(),
  194.                         ],
  195.                         'factoryReviewsUrl' => $factoryReviewsUrl,
  196.                         'avgReviewsStar' => $avgReviewsStar,
  197.                     ]
  198.                 );
  199.                 $key $key ?: $oSSearch->getSearchKey();
  200.                 if (!$oSSearch->getSearchKey()) {
  201.                     $oSSearch->setSearchKey($key);
  202.                 }
  203.             } else {
  204.                 $response = new JsonResponse(
  205.                     [
  206.                         'content' => $this->render('@Web/Catalog/search-result.html.twig'$output)->getContent(),
  207.                         'page' => $oSSearch->getPage(),
  208.                         'pageCount' => $pageCount,
  209.                         'limit' => $limit,
  210.                         'count' => $result['count'],
  211.                     ]
  212.                 );
  213.             }
  214.         } else {
  215.             $response $this->render('@Web/Catalog/index.html.twig'$output); // 179 ms
  216.         }
  217.         // чистим временную сортировку каталога
  218.         App::getSession()->remove('sort_catalog_tmp');
  219.         return $response;
  220.     }
  221.     /**
  222.      * @param string $key
  223.      * @param        $filterKey
  224.      * @return Response
  225.      * @throws Exception
  226.      */
  227.     public function filtersAction(string $key$filterKey)
  228.     {
  229.         $_locale App::getRequest()->get('_locale');
  230.         $_locale $_locale ?: App::getCurLocale();
  231.         //////////////////////////////////////
  232.         // заплатка для локагей вида en_us
  233.         // разбираем локаль и формируем на основании первой части
  234.         // на выдачу меняем локаль сформированную на исходную
  235.         $a_locale explode('-'$_locale);
  236.         $_locale_replace null;
  237.         if (count($a_locale) > 1) {
  238.             $_locale_replace $_locale;
  239.             $_locale $a_locale[0];
  240.         }
  241.         //////////////////////////////////////
  242.         // запрос фильтрации НЕ из каталога через лефт меню
  243.         if ($key == 'add') {
  244.             $word FilterHelper::getWord(null$_locale);
  245.             $url FilterHelper::getUrl(null$_locale$_locale_replace);
  246.             return $this->ok([
  247.                 'post' => RequestHelper::get(),
  248.                 'url' => $url,
  249.                 'word' => $word,
  250.             ]);
  251.         } elseif ($key == 'get-uri') {
  252.             $word FilterHelper::getWord($filterKey$_locale);
  253.             $url FilterHelper::getUrl($filterKey$_locale$_locale_replace);
  254.             return $this->ok([
  255.                 'url' => $url,
  256.                 'word' => $word,
  257.                 '$key' => $key,
  258.                 '_locale' => $_locale,
  259.                 '$filterKey' => $filterKey,
  260.             ]);
  261.         } elseif ($key == 'list-designer') {
  262.             $isReact $filterKey == 'react';
  263.             $aids = [];
  264.             // адский костыль, но пока иначе никак
  265.             // получаем выдачу коллекций и по ним формируем список дизайнеров
  266.             $referer = !empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
  267.             if ($referer) {
  268.                 $keyNorm explode('/'$referer);
  269.                 $keyNorm array_pop($keyNorm);
  270.                 $keyNorm explode('?'$keyNorm);
  271.                 $keyNorm $keyNorm[0];
  272.                 $keyNorm explode('&'$keyNorm);
  273.                 $searchFilter $this->filterRepository->getFiltersForSearchSphinx($keyNorm$_locale);
  274.                 $data = [
  275.                     "searchFilter" => $searchFilter,
  276.                     "searchSort" => "3",
  277.                     "searchPeriod" => null,
  278.                     "locale" => $_locale,
  279.                 ];
  280.                 $sphRes $this->sphinxSearcherService->searchSphinx($data3falsetruetrue);
  281.                 $allCalculate $sphRes['res']['calculate'] ?? $sphRes['calculate'];
  282.                 $sphRes $sphRes['res']['collections'] ?? $sphRes['collections'];
  283.                 $cids array_column($sphRes'c_id');
  284.                 if ($cids) {
  285.                     $aids $this->collectionRepository->getCollAuthorIds($cids);
  286.                 }
  287.             }
  288.             // получение и формирования списка дизайнеров в каталоге /.../catalogue/designer
  289.             $listDesigner $this->filterRepository->getListDesignersForCataloge($aids);
  290.             $listDesignersCnt count($listDesigner);
  291.             $aLlistDesigner = [];
  292.             $keyDesignerStyle $this->filterRepository->getKeyDesignerStyle($_locale);
  293.             $keysNew = !empty($keyNorm) ? array_diff($keyNorm, [$keyDesignerStyle]) : [];
  294.             foreach ($listDesigner as $des) {
  295.                 $firstLetter $des['name'][0];
  296.                 $des['slug'] .= !empty($keysNew) ? '&' implode('&'$keysNew) : '';
  297.                 $des['url'] = urldecode($this->generateUrl('app_catalog', ['key' => $des['slug']]));
  298.                 $des['active'] = $filterKey == $des['oldId'];
  299.                 $des['cnt'] = $allCalculate['getDesigner'][$des['id']] ?? 0;
  300.                 if ($des['cnt']) {
  301.                     $aLlistDesigner[$firstLetter][] = $des;
  302.                 }
  303.             }
  304.             if ($isReact) {
  305.                 $content $aLlistDesigner;
  306.             } else {
  307.                 $output $this->render('@Web/Catalog/menu_designers.html.twig', ['listDesigners' => $aLlistDesigner]);
  308.                 $content $output->getContent();
  309.             }
  310.             return $this->ok([
  311.                 'allCount' => $listDesignersCnt,
  312.                 'content' => $content,
  313.             ]);
  314.         } else {
  315.             return $this->error("fail filtersAction not $key");
  316.         }
  317.     }
  318. }