<?php
namespace MoorlInterrupter\Storefront\Subscriber;
use MoorlInterrupter\Core\Content\Interrupter\InterrupterCollection;
use Shopware\Core\Content\Cms\DataResolver\CmsSlotsDataResolver;
use Shopware\Core\Content\Cms\DataResolver\ResolverContext\ResolverContext;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Framework\DataAbstractionLayer\DefinitionInstanceRegistry;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\RangeFilter;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductListingSubscriber implements EventSubscriberInterface
{
private DefinitionInstanceRegistry $definitionInstanceRegistry;
private SystemConfigService $systemConfigService;
private CmsSlotsDataResolver $resolver;
public function __construct(
DefinitionInstanceRegistry $definitionInstanceRegistry,
SystemConfigService $systemConfigService,
CmsSlotsDataResolver $resolver
)
{
$this->definitionInstanceRegistry = $definitionInstanceRegistry;
$this->systemConfigService = $systemConfigService;
$this->resolver = $resolver;
}
public static function getSubscribedEvents(): array
{
return [
ProductListingResultEvent::class => 'onProductListingResult',
];
}
public function onProductListingResult(ProductListingResultEvent $event): void
{
$salesChannelContext = $event->getSalesChannelContext();
$result = $event->getResult();
$request = $event->getRequest();
$navigationId = $result->getCurrentFilter('navigationId');
if (!$navigationId) {
return;
}
$time = (new \DateTimeImmutable())->format(DATE_ATOM);
$criteria = new Criteria();
$criteria->addFilter(new MultiFilter(MultiFilter::CONNECTION_AND, [
new EqualsFilter('active', true),
new EqualsFilter('categories.id', $navigationId),
new RangeFilter('minResults', ['lte' => $result->count()]),
new MultiFilter(
MultiFilter::CONNECTION_OR, [
new EqualsFilter('showFrom', null),
new RangeFilter('showFrom', ['lte' => $time])
]
),
new MultiFilter(
MultiFilter::CONNECTION_OR, [
new EqualsFilter('showUntil', null),
new RangeFilter('showUntil', ['gte' => $time])
]
),
new MultiFilter(
MultiFilter::CONNECTION_OR, [
new EqualsFilter('page', 0),
new EqualsFilter('page', $result->getPage())
]
)
]));
$repo = $this->definitionInstanceRegistry->getRepository('moorl_interrupter');
/** @var InterrupterCollection $moorlInterrupters */
$moorlInterrupters = $repo->search($criteria, $salesChannelContext->getContext())->getEntities();
if ($moorlInterrupters->count() === 0) {
return;
}
$resolverContext = new ResolverContext($salesChannelContext, $request);
$this->resolver->resolve($moorlInterrupters, $resolverContext);
$result->assign([
'moorlInterrupters' => $moorlInterrupters
]);
}
}