custom/plugins/HBCTheme/src/Controller/DetailedSearchController.php line 220

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace HBCTheme\Controller;
  3. use Shopware\Core\Content\Product\Exception\ProductNotFoundException;
  4. use Shopware\Core\Content\Product\SalesChannel\Search\AbstractProductSearchRoute;
  5. use Shopware\Core\Content\Product\SalesChannel\Suggest\AbstractProductSuggestRoute;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\AndFilter;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  11. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  12. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
  13. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NotFilter;
  14. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  15. use Shopware\Core\Framework\Routing\Annotation\Since;
  16. use Shopware\Core\Framework\Routing\Exception\MissingRequestParameterException;
  17. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  18. use Shopware\Storefront\Controller\StorefrontController;
  19. use Shopware\Storefront\Framework\Cache\Annotation\HttpCache;
  20. use Shopware\Storefront\Page\GenericPageLoaderInterface;
  21. use Shopware\Storefront\Page\Search\SearchPageLoader;
  22. use Shopware\Storefront\Page\Suggest\SuggestPage;
  23. use Shopware\Storefront\Page\Suggest\SuggestPageLoadedEvent;
  24. use Shopware\Storefront\Page\Suggest\SuggestPageLoader;
  25. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  26. use Symfony\Component\HttpFoundation\JsonResponse;
  27. use Symfony\Component\HttpFoundation\Request;
  28. use Symfony\Component\HttpFoundation\Response;
  29. use Symfony\Component\Routing\Annotation\Route;
  30. /**
  31.  * @RouteScope(scopes={"storefront"})
  32.  */
  33. class DetailedSearchController extends StorefrontController
  34. {
  35.     /**
  36.      * @var SearchPageLoader
  37.      */
  38.     private $searchPageLoader;
  39.     /**
  40.      * @var SuggestPageLoader
  41.      */
  42.     private $suggestPageLoader;
  43.     /**
  44.      * @var AbstractProductSearchRoute
  45.      */
  46.     private $productSearchRoute;
  47.     /**
  48.      * @var EntityRepositoryInterface
  49.      */
  50.     private $productRepository;
  51.     /**
  52.      * @var EventDispatcherInterface
  53.      */
  54.     private $eventDispatcher;
  55.     /**
  56.      * @var AbstractProductSuggestRoute
  57.      */
  58.     private $productSuggestRoute;
  59.     /**
  60.      * @var GenericPageLoaderInterface
  61.      */
  62.     private $genericLoader;
  63.     public function __construct(
  64.         SearchPageLoader $searchPageLoader,
  65.         SuggestPageLoader $suggestPageLoader,
  66.         AbstractProductSearchRoute $productSearchRoute,
  67.         EntityRepositoryInterface $productRepository,
  68.         EventDispatcherInterface $eventDispatcher,
  69.         AbstractProductSuggestRoute $productSuggestRoute,
  70.         GenericPageLoaderInterface $genericLoader
  71.     ) {
  72.         $this->searchPageLoader $searchPageLoader;
  73.         $this->suggestPageLoader $suggestPageLoader;
  74.         $this->productSearchRoute $productSearchRoute;
  75.         $this->productRepository $productRepository;
  76.         $this->eventDispatcher $eventDispatcher;
  77.         $this->productSuggestRoute $productSuggestRoute;
  78.         $this->genericLoader $genericLoader;
  79.     }
  80.     /**
  81.      * @Since("6.0.0.0")
  82.      * @HttpCache()
  83.      * @Route("/detailedsearch", name="frontend.search.page", methods={"GET"})
  84.      */
  85.     public function search(SalesChannelContext $contextRequest $request): Response
  86.     {
  87.         try {
  88.             $page $this->searchPageLoader->load($request$context);
  89.             $searchterm $page->getSearchTerm();
  90.             $productId $this->productRepository->search((new Criteria())->addAssociation('visibility')
  91.                 ->addAssociation('translations')
  92.                 ->addFilter(new MultiFilter(MultiFilter::CONNECTION_AND, [
  93.                     new MultiFilter(MultiFilter::CONNECTION_OR, [
  94.                         new EqualsFilter('productNumber'$searchterm),
  95.                         new EqualsFilter('ean'$searchterm),
  96.                         new EqualsFilter('product.translations.name'$searchterm)
  97.                     ]),
  98.                     new NotFilter(NotFilter::CONNECTION_OR, [
  99.                        new EqualsFilter('parentId'null)
  100.                     ]),
  101.                     new EqualsFilter('visibilities.salesChannelId'$context->getSalesChannelId()),
  102.                     new EqualsFilter('active'true)
  103.                 ]))
  104.                , $context->getContext())->first();
  105.            // file_put_contents('log/searchids.txt', PHP_EOL . PHP_EOL . $searchterm,  FILE_APPEND);
  106.             if($productId)
  107.             {
  108.                 try {
  109.                     return $this->forwardToRoute('frontend.detail.page', [], ['productId' => $productId->getId()]);
  110.                 }catch (\Exception $e)
  111.                 {
  112.                     if ($page->getListing()->getTotal() === 1) {
  113.                         $product $page->getListing()->first();
  114.                         if ($request->get('search') === $product->getProductNumber()) {
  115.                             $productId $product->getId();
  116.                             return $this->forwardToRoute('frontend.detail.page', [], ['productId' => $productId]);
  117.                         }
  118.                     }
  119.                 } catch (MissingRequestParameterException $missingRequestParameterException) {
  120.                     return $this->forwardToRoute('frontend.home.page');
  121.                 }
  122.             }
  123.             if ($page->getListing()->getTotal() === 1) {
  124.                 $product $page->getListing()->first();
  125.                 if ($request->get('search') === $product->getProductNumber()) {
  126.                     $productId $product->getId();
  127.                     return $this->forwardToRoute('frontend.detail.page', [], ['productId' => $productId]);
  128.                 }
  129.             }
  130.         } catch (MissingRequestParameterException $missingRequestParameterException) {
  131.             return $this->forwardToRoute('frontend.home.page');
  132.         }
  133.         return $this->renderStorefront('@Storefront/storefront/page/search/index.html.twig', ['page' => $page]);
  134.     }
  135.     /**
  136.      * @Since("6.0.0.0")
  137.      * @HttpCache()
  138.      * @Route("/suggest", name="frontend.search.suggest", methods={"GET"}, defaults={"XmlHttpRequest"=true})
  139.      */
  140.     public function suggest(SalesChannelContext $contextRequest $request): Response
  141.     {
  142.         $ids = [];
  143.         $page $this->genericLoader->load($request$context);
  144.         $page SuggestPage::createFrom($page);
  145.         $page->setSearchTerm($request->query->get('search'));
  146.         $searchterm $page->getSearchTerm();
  147.         if( (strlen($searchterm) > 5))
  148.         {
  149.                 $criteria = (new Criteria())->addAssociation('visibility')
  150.                 ->addAssociation('translations')
  151.                 ->addFilter(new MultiFilter(MultiFilter::CONNECTION_AND, [
  152.                     new MultiFilter(MultiFilter::CONNECTION_OR, [
  153.                         new EqualsFilter('productNumber'$searchterm),
  154.                         new EqualsFilter('ean'$searchterm),
  155.                         new EqualsFilter('product.translations.name'$searchterm)
  156.                     ]),
  157.                     new NotFilter(NotFilter::CONNECTION_AND, [
  158.                         new EqualsFilter('parentId'null),
  159.                         new EqualsFilter('product.translations.name'$searchterm)
  160.                     ]),
  161.                     new EqualsFilter('visibilities.salesChannelId'$context->getSalesChannelId()),
  162.                     new EqualsFilter('active'true)
  163.                 ]));
  164.             $products $this->productRepository->search($criteria$context->getContext());
  165.            $ids $products->getIds();
  166.         }
  167.         $criteria = new Criteria();
  168.         if(($ids)) {
  169.             $criteria->setIds$ids);
  170.         }
  171.         $criteria->setLimit(10);
  172.         $criteria->addAssociation('properties.group');
  173.         $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_EXACT);
  174.         $page->setSearchResult(
  175.             $this->productSuggestRoute
  176.                 ->load($request$context$criteria)
  177.                 ->getListingResult()
  178.         );
  179.        // $page->setSearchTerm($request->query->get('search'));
  180.         $this->eventDispatcher->dispatch(
  181.             new SuggestPageLoadedEvent($page$context$request)
  182.         );
  183.         return $this->renderStorefront('@Storefront/storefront/layout/header/search-suggest.html.twig', ['page' => $page]);
  184.     }
  185.     /**
  186.      * @Since("6.2.0.0")
  187.      * @HttpCache()
  188.      *
  189.      * Route to load the listing filters
  190.      *
  191.      * @RouteScope(scopes={"storefront"})
  192.      * @Route("/widgets/search", name="widgets.search.pagelet.v2", methods={"GET", "POST"}, defaults={"XmlHttpRequest"=true})
  193.      *
  194.      * @throws MissingRequestParameterException
  195.      */
  196.     public function ajax(Request $requestSalesChannelContext $context): Response
  197.     {
  198.         $request->request->set('no-aggregations'true);
  199.         $page $this->searchPageLoader->load($request$context);
  200.         $response $this->renderStorefront('@Storefront/storefront/page/search/search-pagelet.html.twig', ['page' => $page]);
  201.         $response->headers->set('x-robots-tag''noindex');
  202.         return $response;
  203.     }
  204.     /**
  205.      * @Since("6.3.3.0")
  206.      * @HttpCache()
  207.      *
  208.      * Route to load the available listing filters
  209.      *
  210.      * @RouteScope(scopes={"storefront"})
  211.      * @Route("/widgets/search/filter", name="widgets.search.filter", methods={"GET", "POST"}, defaults={"XmlHttpRequest"=true})
  212.      *
  213.      * @throws MissingRequestParameterException
  214.      */
  215.     public function filter(Request $requestSalesChannelContext $context): Response
  216.     {
  217.         $term $request->get('search');
  218.         if (!$term) {
  219.             throw new MissingRequestParameterException('search');
  220.         }
  221.         // Allows to fetch only aggregations over the gateway.
  222.         $request->request->set('only-aggregations'true);
  223.         // Allows to convert all post-filters to filters. This leads to the fact that only aggregation values are returned, which are combinable with the previous applied filters.
  224.         $request->request->set('reduce-aggregations'true);
  225.         $criteria = new Criteria();
  226.         $criteria->setTitle('search-page');
  227.         $result $this->productSearchRoute
  228.             ->load($request$context$criteria)
  229.             ->getListingResult();
  230.         $mapped = [];
  231.         foreach ($result->getAggregations() as $aggregation) {
  232.             $mapped[$aggregation->getName()] = $aggregation;
  233.         }
  234.         $response = new JsonResponse($mapped);
  235.         $response->headers->set('x-robots-tag''noindex');
  236.         return $response;
  237.     }
  238. }