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

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