<?php
declare(strict_types=1);
namespace ShortStories\Subscriber;
use Shopware\Core\Content\Product\Events\ProductListingCollectFilterEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Content\Product\SalesChannel\Listing\Filter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Bucket\FilterAggregation;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\MaxAggregation;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\EntityAggregation;
use Shopware\Core\Content\Product\SalesChannel\Listing\ProductListingResult;
use Symfony\Component\HttpFoundation\Request;
class ListingSubscriber implements EventSubscriberInterface
{
// register event
public static function getSubscribedEvents(): array
{
return [
ProductListingCollectFilterEvent::class => 'addFilter'
];
}
public function addFilter(ProductListingCollectFilterEvent $event): void
{
// fetch existing filters
$filters = $event->getFilters();
$request = $event->getRequest();
$ids = $this->getPropIds($request, "material");
$filter = new Filter(
// name
'material',
// filtered
!empty($ids),
// aggregations
[
new FilterAggregation(
'material-filter',
new MaxAggregation('material', 'product.customFields.custom_product_material'),
[new EqualsAnyFilter('product.customFields.custom_product_material', ['423f19d967d843bba8166dadfec585a6'] )]
),
],
new EqualsAnyFilter('product.customFields.custom_product_material', $ids),
// values
$ids
);
// Add your custom filter
$filters->add($filter);
}
protected function getPropIds(Request $request, string $prop = "tag", ?array $defaultIds = null): array
{
$ids = $request->query->get($prop);
if ($request->isMethod(Request::METHOD_POST)) {
$ids = $request->request->get($prop);
}
if (\is_string($ids)) {
$ids = explode('|', $ids);
}
if (empty($ids) && !empty($defaultIds)) {
$ids = $defaultIds;
}
return array_filter((array) $ids);
}
}