<?php declare(strict_types=1);
namespace Cbax\ModulGoogleShopping\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Content\ProductExport\Event\ProductExportRenderBodyContextEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
class BackendSubscriber implements EventSubscriberInterface
{
/** Repository */
private $categoryRepository;
public function __construct(
EntityRepositoryInterface $categories
) {
$this->categoryRepository = $categories;
}
public static function getSubscribedEvents(): array
{
return[
ProductExportRenderBodyContextEvent::class => 'onProductExportRenderBodyContext'
];
}
public function onProductExportRenderBodyContext( ProductExportRenderBodyContextEvent $productExportContext, $context)
{
$newContext = $productExportContext->getContext();
$footerTemplate = $newContext['productExport']->getFooterTemplate();
if (empty($footerTemplate)) return;
if (strpos($footerTemplate, 'CbaxGoogleShopping') === FALSE) return;
$navigationId = $newContext['context']->getSalesChannel()->getNavigationCategoryId();
$salesChannelContext = $newContext['context'];
//Get all Categories where navigationId is in path
$criteria = new Criteria();
$criteria->addFilter(new ContainsFilter('path', $navigationId));
$categoriesResult = $this->categoryRepository->search($criteria, $salesChannelContext->getContext());
$salesChannelCategories = $this->prepareSaleChannelCategories($categoriesResult);
$newContext['cbaxSalesChannelCategories'] = $salesChannelCategories;
$productExportContext->setContext($newContext);
}
private function prepareSaleChannelCategories($categoryCollection) {
$categories = [];
foreach ($categoryCollection->getElements() as $category) {
if (!empty($category->get('translated')['customFields']['cbaxGoogleCategory'])) {
$categories[$category->get('id')] = $category->get('translated')['customFields']['cbaxGoogleCategory'];
}
}
return $categories;
}
}