<?php declare(strict_types=1);
namespace Cbax\ModulAdcell\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
use Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Core\PlatformRequest;
class BackendSubscriber implements EventSubscriberInterface
{
const CONFIG_PATH = 'CbaxModulAdcell.config';
private $config = null;
/**
* @var SystemConfigService
*/
private $systemConfigService;
/**
* @var EntityRepositoryInterface
*/
private $productRepository;
public function __construct(
SystemConfigService $systemConfigService,
EntityRepositoryInterface $productRepository
)
{
$this->systemConfigService = $systemConfigService;
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
return[
NavigationPageLoadedEvent::class => 'onNavigationPageLoaded'
];
}
public function onNavigationPageLoaded(NavigationPageLoadedEvent $event)
{
$request = $event->getRequest();
$salesChannelId = $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT)->getSalesChannelId();
$this->config = $this->config ?? $this->systemConfigService->get(self::CONFIG_PATH, $salesChannelId);
if (empty($this->config['active']) || empty($this->config['retargeting']) || empty($this->config['pubId'])) return;
if (!isset($_COOKIE['adcell-enabled'])) return;
$page = $event->getPage();
$activeCategory = $page->getHeader()->getNavigation()->getActive();
if (empty($activeCategory)) return;
if ($activeCategory->getTranslated()['name'] === 'Home') return;
$criteria = new Criteria();
$criteria->setLimit(20);
$criteria->addFilter(new EqualsFilter('parentId', null));
$criteria->addFilter(new ContainsFilter('categoryTree', $activeCategory->getId()));
$products = $this->productRepository->search($criteria, $event->getContext());
if (!empty($products) && !empty($products->getElements()))
{
$productNumbers = [];
foreach ($products->getElements() as $prod)
{
$productNumbers[] = $prod->getProductNumber();
}
$productNumbersString = implode(';', $productNumbers);
$page->assign( ['cbaxProductIdsForAdcell' => $productNumbersString]);
}
}
}