vendor/shopware/core/Content/Product/SalesChannel/Listing/ProductListingFeaturesSubscriber.php line 134

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Content\Product\SalesChannel\Listing;
  3. use Doctrine\DBAL\Connection;
  4. use Shopware\Core\Content\Product\Events\ProductListingCollectFilterEvent;
  5. use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
  6. use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
  7. use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
  8. use Shopware\Core\Content\Product\Events\ProductSearchResultEvent;
  9. use Shopware\Core\Content\Product\Events\ProductSuggestCriteriaEvent;
  10. use Shopware\Core\Content\Product\SalesChannel\Exception\ProductSortingNotFoundException;
  11. use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingCollection;
  12. use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingEntity;
  13. use Shopware\Core\Content\Property\Aggregate\PropertyGroupOption\PropertyGroupOptionCollection;
  14. use Shopware\Core\Framework\Context;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Dbal\Common\RepositoryIterator;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Doctrine\FetchModeHelper;
  17. use Shopware\Core\Framework\DataAbstractionLayer\EntityCollection;
  18. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  19. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\FilterAggregation;
  20. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\TermsAggregation;
  21. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\EntityAggregation;
  22. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\MaxAggregation;
  23. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\StatsAggregation;
  24. use Shopware\Core\Framework\DataAbstractionLayer\Search\AggregationResult\Bucket\TermsResult;
  25. use Shopware\Core\Framework\DataAbstractionLayer\Search\AggregationResult\Metric\EntityResult;
  26. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  27. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  28. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  29. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
  30. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\RangeFilter;
  31. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  32. use Shopware\Core\Framework\Uuid\Uuid;
  33. use Shopware\Core\Profiling\Profiler;
  34. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  35. use Shopware\Core\System\SystemConfig\SystemConfigService;
  36. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  37. use Symfony\Component\HttpFoundation\Request;
  38. use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
  39. class ProductListingFeaturesSubscriber implements EventSubscriberInterface
  40. {
  41.     public const DEFAULT_SEARCH_SORT 'score';
  42.     public const PROPERTY_GROUP_IDS_REQUEST_PARAM 'property-whitelist';
  43.     /**
  44.      * @var EntityRepositoryInterface
  45.      */
  46.     private $optionRepository;
  47.     /**
  48.      * @var EntityRepositoryInterface
  49.      */
  50.     private $sortingRepository;
  51.     /**
  52.      * @var Connection
  53.      */
  54.     private $connection;
  55.     /**
  56.      * @var SystemConfigService
  57.      */
  58.     private $systemConfigService;
  59.     /**
  60.      * @var EventDispatcherInterface
  61.      */
  62.     private $dispatcher;
  63.     /**
  64.      * @internal
  65.      */
  66.     public function __construct(
  67.         Connection $connection,
  68.         EntityRepositoryInterface $optionRepository,
  69.         EntityRepositoryInterface $productSortingRepository,
  70.         SystemConfigService $systemConfigService,
  71.         EventDispatcherInterface $dispatcher
  72.     ) {
  73.         $this->optionRepository $optionRepository;
  74.         $this->sortingRepository $productSortingRepository;
  75.         $this->connection $connection;
  76.         $this->systemConfigService $systemConfigService;
  77.         $this->dispatcher $dispatcher;
  78.     }
  79.     public static function getSubscribedEvents(): array
  80.     {
  81.         return [
  82.             ProductListingCriteriaEvent::class => [
  83.                 ['handleListingRequest'100],
  84.                 ['handleFlags', -100],
  85.             ],
  86.             ProductSuggestCriteriaEvent::class => [
  87.                 ['handleFlags', -100],
  88.             ],
  89.             ProductSearchCriteriaEvent::class => [
  90.                 ['handleSearchRequest'100],
  91.                 ['handleFlags', -100],
  92.             ],
  93.             ProductListingResultEvent::class => [
  94.                 ['handleResult'100],
  95.                 ['removeScoreSorting', -100],
  96.             ],
  97.             ProductSearchResultEvent::class => 'handleResult',
  98.         ];
  99.     }
  100.     public function handleFlags(ProductListingCriteriaEvent $event): void
  101.     {
  102.         $request $event->getRequest();
  103.         $criteria $event->getCriteria();
  104.         if ($request->get('no-aggregations')) {
  105.             $criteria->resetAggregations();
  106.         }
  107.         if ($request->get('only-aggregations')) {
  108.             // set limit to zero to fetch no products.
  109.             $criteria->setLimit(0);
  110.             // no total count required
  111.             $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_NONE);
  112.             // sorting and association are only required for the product data
  113.             $criteria->resetSorting();
  114.             $criteria->resetAssociations();
  115.         }
  116.     }
  117.     public function handleListingRequest(ProductListingCriteriaEvent $event): void
  118.     {
  119.         $request $event->getRequest();
  120.         $criteria $event->getCriteria();
  121.         $context $event->getSalesChannelContext();
  122.         if (!$request->get('order')) {
  123.             $request->request->set('order'$this->getSystemDefaultSorting($context));
  124.         }
  125.         $criteria->addAssociation('options');
  126.         $this->handlePagination($request$criteria$event->getSalesChannelContext());
  127.         $this->handleFilters($request$criteria$context);
  128.         $this->handleSorting($request$criteria$context);
  129.     }
  130.     public function handleSearchRequest(ProductSearchCriteriaEvent $event): void
  131.     {
  132.         $request $event->getRequest();
  133.         $criteria $event->getCriteria();
  134.         $context $event->getSalesChannelContext();
  135.         if (!$request->get('order')) {
  136.             $request->request->set('order'self::DEFAULT_SEARCH_SORT);
  137.         }
  138.         $this->handlePagination($request$criteria$event->getSalesChannelContext());
  139.         $this->handleFilters($request$criteria$context);
  140.         $this->handleSorting($request$criteria$context);
  141.     }
  142.     public function handleResult(ProductListingResultEvent $event): void
  143.     {
  144.         Profiler::trace('product-listing::feature-subscriber', function () use ($event): void {
  145.             $this->groupOptionAggregations($event);
  146.             $this->addCurrentFilters($event);
  147.             $result $event->getResult();
  148.             /** @var ProductSortingCollection $sortings */
  149.             $sortings $result->getCriteria()->getExtension('sortings');
  150.             $currentSortingKey $this->getCurrentSorting($sortings$event->getRequest())->getKey();
  151.             $result->setSorting($currentSortingKey);
  152.             $result->setAvailableSortings($sortings);
  153.             $result->setPage($this->getPage($event->getRequest()));
  154.             $result->setLimit($this->getLimit($event->getRequest(), $event->getSalesChannelContext()));
  155.         });
  156.     }
  157.     public function removeScoreSorting(ProductListingResultEvent $event): void
  158.     {
  159.         $sortings $event->getResult()->getAvailableSortings();
  160.         $defaultSorting $sortings->getByKey(self::DEFAULT_SEARCH_SORT);
  161.         if ($defaultSorting !== null) {
  162.             $sortings->remove($defaultSorting->getId());
  163.         }
  164.         $event->getResult()->setAvailableSortings($sortings);
  165.     }
  166.     private function handleFilters(Request $requestCriteria $criteriaSalesChannelContext $context): void
  167.     {
  168.         $criteria->addAssociation('manufacturer');
  169.         $filters $this->getFilters($request$context);
  170.         $aggregations $this->getAggregations($request$filters);
  171.         foreach ($aggregations as $aggregation) {
  172.             $criteria->addAggregation($aggregation);
  173.         }
  174.         foreach ($filters as $filter) {
  175.             if ($filter->isFiltered()) {
  176.                 $criteria->addPostFilter($filter->getFilter());
  177.             }
  178.         }
  179.         $criteria->addExtension('filters'$filters);
  180.     }
  181.     private function getAggregations(Request $requestFilterCollection $filters): array
  182.     {
  183.         $aggregations = [];
  184.         if ($request->get('reduce-aggregations') === null) {
  185.             foreach ($filters as $filter) {
  186.                 $aggregations array_merge($aggregations$filter->getAggregations());
  187.             }
  188.             return $aggregations;
  189.         }
  190.         foreach ($filters as $filter) {
  191.             $excluded $filters->filtered();
  192.             if ($filter->exclude()) {
  193.                 $excluded $excluded->blacklist($filter->getName());
  194.             }
  195.             foreach ($filter->getAggregations() as $aggregation) {
  196.                 if ($aggregation instanceof FilterAggregation) {
  197.                     $aggregation->addFilters($excluded->getFilters());
  198.                     $aggregations[] = $aggregation;
  199.                     continue;
  200.                 }
  201.                 $aggregation = new FilterAggregation(
  202.                     $aggregation->getName(),
  203.                     $aggregation,
  204.                     $excluded->getFilters()
  205.                 );
  206.                 $aggregations[] = $aggregation;
  207.             }
  208.         }
  209.         return $aggregations;
  210.     }
  211.     private function handlePagination(Request $requestCriteria $criteriaSalesChannelContext $context): void
  212.     {
  213.         $limit $this->getLimit($request$context);
  214.         $page $this->getPage($request);
  215.         $criteria->setOffset(($page 1) * $limit);
  216.         $criteria->setLimit($limit);
  217.         $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_EXACT);
  218.     }
  219.     private function handleSorting(Request $requestCriteria $criteriaSalesChannelContext $context): void
  220.     {
  221.         /** @var ProductSortingCollection $sortings */
  222.         $sortings $criteria->getExtension('sortings') ?? new ProductSortingCollection();
  223.         $sortings->merge($this->getAvailableSortings($request$context->getContext()));
  224.         $currentSorting $this->getCurrentSorting($sortings$request);
  225.         $criteria->addSorting(
  226.             ...$currentSorting->createDalSorting()
  227.         );
  228.         $criteria->addExtension('sortings'$sortings);
  229.     }
  230.     private function getCurrentSorting(ProductSortingCollection $sortingsRequest $request): ProductSortingEntity
  231.     {
  232.         $key $request->get('order');
  233.         $sorting $sortings->getByKey($key);
  234.         if ($sorting !== null) {
  235.             return $sorting;
  236.         }
  237.         throw new ProductSortingNotFoundException($key);
  238.     }
  239.     private function getAvailableSortings(Request $requestContext $context): EntityCollection
  240.     {
  241.         $criteria = new Criteria();
  242.         $criteria->setTitle('product-listing::load-sortings');
  243.         $availableSortings $request->get('availableSortings');
  244.         $availableSortingsFilter = [];
  245.         if ($availableSortings) {
  246.             arsort($availableSortings\SORT_DESC \SORT_NUMERIC);
  247.             $availableSortingsFilter array_keys($availableSortings);
  248.             $criteria->addFilter(new EqualsAnyFilter('key'$availableSortingsFilter));
  249.         }
  250.         $criteria
  251.             ->addFilter(new EqualsFilter('active'true))
  252.             ->addSorting(new FieldSorting('priority''DESC'));
  253.         /** @var ProductSortingCollection $sortings */
  254.         $sortings $this->sortingRepository->search($criteria$context)->getEntities();
  255.         if ($availableSortings) {
  256.             $sortings->sortByKeyArray($availableSortingsFilter);
  257.         }
  258.         return $sortings;
  259.     }
  260.     private function getSystemDefaultSorting(SalesChannelContext $context): string
  261.     {
  262.         return $this->systemConfigService->getString(
  263.             'core.listing.defaultSorting',
  264.             $context->getSalesChannel()->getId()
  265.         );
  266.     }
  267.     private function collectOptionIds(ProductListingResultEvent $event): array
  268.     {
  269.         $aggregations $event->getResult()->getAggregations();
  270.         /** @var TermsResult|null $properties */
  271.         $properties $aggregations->get('properties');
  272.         /** @var TermsResult|null $options */
  273.         $options $aggregations->get('options');
  274.         $options $options $options->getKeys() : [];
  275.         $properties $properties $properties->getKeys() : [];
  276.         return array_unique(array_filter(array_merge($options$properties)));
  277.     }
  278.     private function groupOptionAggregations(ProductListingResultEvent $event): void
  279.     {
  280.         $ids $this->collectOptionIds($event);
  281.         if (empty($ids)) {
  282.             return;
  283.         }
  284.         $criteria = new Criteria($ids);
  285.         $criteria->setLimit(500);
  286.         $criteria->addAssociation('group');
  287.         $criteria->addAssociation('media');
  288.         $criteria->addFilter(new EqualsFilter('group.filterable'true));
  289.         $criteria->setTitle('product-listing::property-filter');
  290.         $criteria->addSorting(new FieldSorting('id'FieldSorting::ASCENDING));
  291.         $mergedOptions = new PropertyGroupOptionCollection();
  292.         $repositoryIterator = new RepositoryIterator($this->optionRepository$event->getContext(), $criteria);
  293.         while (($result $repositoryIterator->fetch()) !== null) {
  294.             $mergedOptions->merge($result->getEntities());
  295.         }
  296.         // group options by their property-group
  297.         $grouped $mergedOptions->groupByPropertyGroups();
  298.         $grouped->sortByPositions();
  299.         $grouped->sortByConfig();
  300.         $aggregations $event->getResult()->getAggregations();
  301.         // remove id results to prevent wrong usages
  302.         $aggregations->remove('properties');
  303.         $aggregations->remove('configurators');
  304.         $aggregations->remove('options');
  305.         $aggregations->add(new EntityResult('properties'$grouped));
  306.     }
  307.     private function addCurrentFilters(ProductListingResultEvent $event): void
  308.     {
  309.         $result $event->getResult();
  310.         $filters $result->getCriteria()->getExtension('filters');
  311.         if (!$filters instanceof FilterCollection) {
  312.             return;
  313.         }
  314.         foreach ($filters as $filter) {
  315.             $result->addCurrentFilter($filter->getName(), $filter->getValues());
  316.         }
  317.     }
  318.     private function getManufacturerIds(Request $request): array
  319.     {
  320.         $ids $request->query->get('manufacturer''');
  321.         if ($request->isMethod(Request::METHOD_POST)) {
  322.             $ids $request->request->get('manufacturer''');
  323.         }
  324.         if (\is_string($ids)) {
  325.             $ids explode('|'$ids);
  326.         }
  327.         return array_filter((array) $ids);
  328.     }
  329.     private function getPropertyIds(Request $request): array
  330.     {
  331.         $ids $request->query->get('properties''');
  332.         if ($request->isMethod(Request::METHOD_POST)) {
  333.             $ids $request->request->get('properties''');
  334.         }
  335.         if (\is_string($ids)) {
  336.             $ids explode('|'$ids);
  337.         }
  338.         return array_filter((array) $ids);
  339.     }
  340.     private function getLimit(Request $requestSalesChannelContext $context): int
  341.     {
  342.         $limit $request->query->getInt('limit'0);
  343.         if ($request->isMethod(Request::METHOD_POST)) {
  344.             $limit $request->request->getInt('limit'$limit);
  345.         }
  346.         $limit $limit $limit $this->systemConfigService->getInt('core.listing.productsPerPage'$context->getSalesChannel()->getId());
  347.         return $limit <= 24 $limit;
  348.     }
  349.     private function getPage(Request $request): int
  350.     {
  351.         $page $request->query->getInt('p'1);
  352.         if ($request->isMethod(Request::METHOD_POST)) {
  353.             $page $request->request->getInt('p'$page);
  354.         }
  355.         return $page <= $page;
  356.     }
  357.     private function getFilters(Request $requestSalesChannelContext $context): FilterCollection
  358.     {
  359.         $filters = new FilterCollection();
  360.         $filters->add($this->getManufacturerFilter($request));
  361.         $filters->add($this->getPriceFilter($request));
  362.         $filters->add($this->getRatingFilter($request));
  363.         $filters->add($this->getShippingFreeFilter($request));
  364.         $filters->add($this->getPropertyFilter($request));
  365.         if (!$request->request->get('manufacturer-filter'true)) {
  366.             $filters->remove('manufacturer');
  367.         }
  368.         if (!$request->request->get('price-filter'true)) {
  369.             $filters->remove('price');
  370.         }
  371.         if (!$request->request->get('rating-filter'true)) {
  372.             $filters->remove('rating');
  373.         }
  374.         if (!$request->request->get('shipping-free-filter'true)) {
  375.             $filters->remove('shipping-free');
  376.         }
  377.         if (!$request->request->get('property-filter'true)) {
  378.             $filters->remove('properties');
  379.             if (\count($propertyWhitelist $request->request->all(self::PROPERTY_GROUP_IDS_REQUEST_PARAM))) {
  380.                 $filters->add($this->getPropertyFilter($request$propertyWhitelist));
  381.             }
  382.         }
  383.         $event = new ProductListingCollectFilterEvent($request$filters$context);
  384.         $this->dispatcher->dispatch($event);
  385.         return $filters;
  386.     }
  387.     private function getManufacturerFilter(Request $request): Filter
  388.     {
  389.         $ids $this->getManufacturerIds($request);
  390.         return new Filter(
  391.             'manufacturer',
  392.             !empty($ids),
  393.             [new EntityAggregation('manufacturer''product.manufacturerId''product_manufacturer')],
  394.             new EqualsAnyFilter('product.manufacturerId'$ids),
  395.             $ids
  396.         );
  397.     }
  398.     private function getPropertyFilter(Request $request, ?array $groupIds null): Filter
  399.     {
  400.         $ids $this->getPropertyIds($request);
  401.         $propertyAggregation = new TermsAggregation('properties''product.properties.id');
  402.         $optionAggregation = new TermsAggregation('options''product.options.id');
  403.         if ($groupIds) {
  404.             $propertyAggregation = new FilterAggregation(
  405.                 'properties-filter',
  406.                 $propertyAggregation,
  407.                 [new EqualsAnyFilter('product.properties.groupId'$groupIds)]
  408.             );
  409.             $optionAggregation = new FilterAggregation(
  410.                 'options-filter',
  411.                 $optionAggregation,
  412.                 [new EqualsAnyFilter('product.options.groupId'$groupIds)]
  413.             );
  414.         }
  415.         if (empty($ids)) {
  416.             return new Filter(
  417.                 'properties',
  418.                 false,
  419.                 [$propertyAggregation$optionAggregation],
  420.                 new MultiFilter(MultiFilter::CONNECTION_OR, []),
  421.                 [],
  422.                 false
  423.             );
  424.         }
  425.         $grouped $this->connection->fetchAll(
  426.             'SELECT LOWER(HEX(property_group_id)) as property_group_id, LOWER(HEX(id)) as id
  427.              FROM property_group_option
  428.              WHERE id IN (:ids)',
  429.             ['ids' => Uuid::fromHexToBytesList($ids)],
  430.             ['ids' => Connection::PARAM_STR_ARRAY]
  431.         );
  432.         $grouped FetchModeHelper::group($grouped);
  433.         $filters = [];
  434.         foreach ($grouped as $options) {
  435.             $options array_column($options'id');
  436.             $filters[] = new MultiFilter(
  437.                 MultiFilter::CONNECTION_OR,
  438.                 [
  439.                     new EqualsAnyFilter('product.optionIds'$options),
  440.                     new EqualsAnyFilter('product.propertyIds'$options),
  441.                 ]
  442.             );
  443.         }
  444.         return new Filter(
  445.             'properties',
  446.             true,
  447.             [$propertyAggregation$optionAggregation],
  448.             new MultiFilter(MultiFilter::CONNECTION_AND$filters),
  449.             $ids,
  450.             false
  451.         );
  452.     }
  453.     private function getPriceFilter(Request $request): Filter
  454.     {
  455.         $min $request->get('min-price');
  456.         $max $request->get('max-price');
  457.         $range = [];
  458.         if ($min !== null && $min >= 0) {
  459.             $range[RangeFilter::GTE] = $min;
  460.         }
  461.         if ($max !== null && $max >= 0) {
  462.             $range[RangeFilter::LTE] = $max;
  463.         }
  464.         return new Filter(
  465.             'price',
  466.             !empty($range),
  467.             [new StatsAggregation('price''product.cheapestPrice'truetruefalsefalse)],
  468.             new RangeFilter('product.cheapestPrice'$range),
  469.             [
  470.                 'min' => (float) $request->get('min-price'),
  471.                 'max' => (float) $request->get('max-price'),
  472.             ]
  473.         );
  474.     }
  475.     private function getRatingFilter(Request $request): Filter
  476.     {
  477.         $filtered $request->get('rating');
  478.         return new Filter(
  479.             'rating',
  480.             $filtered !== null,
  481.             [
  482.                 new FilterAggregation(
  483.                     'rating-exists',
  484.                     new MaxAggregation('rating''product.ratingAverage'),
  485.                     [new RangeFilter('product.ratingAverage', [RangeFilter::GTE => 0])]
  486.                 ),
  487.             ],
  488.             new RangeFilter('product.ratingAverage', [
  489.                 RangeFilter::GTE => (int) $filtered,
  490.             ]),
  491.             $filtered
  492.         );
  493.     }
  494.     private function getShippingFreeFilter(Request $request): Filter
  495.     {
  496.         $filtered = (bool) $request->get('shipping-free'false);
  497.         return new Filter(
  498.             'shipping-free',
  499.             $filtered === true,
  500.             [
  501.                 new FilterAggregation(
  502.                     'shipping-free-filter',
  503.                     new MaxAggregation('shipping-free''product.shippingFree'),
  504.                     [new EqualsFilter('product.shippingFree'true)]
  505.                 ),
  506.             ],
  507.             new EqualsFilter('product.shippingFree'true),
  508.             $filtered
  509.         );
  510.     }
  511. }