custom/plugins/System4ShopTheme/src/Subscriber/ThemeSubscriber.php line 23

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace System4ShopTheme\Subscriber;
  3. use Shopware\Core\Content\Product\Events\ProductListingCollectFilterEvent;
  4. use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
  5. use Shopware\Core\Content\Product\SalesChannel\Listing\Filter;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\EntityAggregation;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. class ThemeSubscriber implements EventSubscriberInterface
  11. {
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         // Return the events to listen to as array like this:  <event to listen to> => <method to execute>
  15.         return [
  16.             ProductListingCollectFilterEvent::class => 'addCategoryFilter',
  17.         ];
  18.     }
  19.     public function addCategoryFilter(ProductListingCollectFilterEvent $event)
  20.     {
  21.         $filters $event->getFilters();
  22.         $ids $this->getCategoryIds($event->getRequest());
  23.         $filter = new Filter(
  24.             //unique name of the filter
  25.             'category',
  26.             
  27.             // defines if this filter is active
  28.             !empty($ids),
  29.             
  30.             // defines aggregations behind a filter. Sometimes a filter contains multiple aggregations like properties
  31.             [new EntityAggregation('category''product.categories.id''category')],
  32.             
  33.             // defines the DAL filter which should be added to the criteria   
  34.             new EqualsAnyFilter('product.categories.id'$ids),
  35.             
  36.             // defines the values which will be added as currentFilter to the result
  37.             $ids
  38.         );
  39.         $filters->add($filter);
  40.     }
  41.     private function getCategoryIds(Request $request): array
  42.     {
  43.         $ids $request->query->get('category''');
  44.         $ids explode('|'$ids);
  45.         return array_filter($ids);
  46.     }
  47. }