<?php declare(strict_types=1);
namespace System4ShopTheme\Subscriber;
use Shopware\Core\Content\Product\Events\ProductListingCollectFilterEvent;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Content\Product\SalesChannel\Listing\Filter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\EntityAggregation;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class ThemeSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
// Return the events to listen to as array like this: <event to listen to> => <method to execute>
return [
ProductListingCollectFilterEvent::class => 'addCategoryFilter',
];
}
public function addCategoryFilter(ProductListingCollectFilterEvent $event)
{
$filters = $event->getFilters();
$ids = $this->getCategoryIds($event->getRequest());
$filter = new Filter(
//unique name of the filter
'category',
// defines if this filter is active
!empty($ids),
// defines aggregations behind a filter. Sometimes a filter contains multiple aggregations like properties
[new EntityAggregation('category', 'product.categories.id', 'category')],
// defines the DAL filter which should be added to the criteria
new EqualsAnyFilter('product.categories.id', $ids),
// defines the values which will be added as currentFilter to the result
$ids
);
$filters->add($filter);
}
private function getCategoryIds(Request $request): array
{
$ids = $request->query->get('category', '');
$ids = explode('|', $ids);
return array_filter($ids);
}
}