<?php declare(strict_types=1);
namespace Dupp\Sync4Api\Subscriber;
use Shopware\Core\Content\Category\CategoryEntity;
use Shopware\Core\Content\Category\SalesChannel\AbstractCategoryRoute;
use Shopware\Core\Content\Category\CategoryEvents;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Storefront\Page\Navigation\NavigationPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CategoryLoadedSubscriber implements EventSubscriberInterface
{
/**
* @var AbstractCategoryRoute
*/
private $cmsPageRoute;
public function __construct(
AbstractCategoryRoute $cmsPageRoute
)
{
$this->cmsPageRoute = $cmsPageRoute;
}
/**
* @var string
*/
private $pluginName = 'Sync4ApiExport';
/**
* @var string
*/
private $customFieldName = 'sync4_api_visual_order';
public static function getSubscribedEvents(): array
{
return [
NavigationPageLoadedEvent::class => 'onNavigationPageLoaded'
];
}
public function onNavigationPageLoaded(NavigationPageLoadedEvent $event)
{
try {
$this->handleCustomFields($event);
} catch (\Exception $exception) {
//TODO: add logging
}
}
private function handleCustomFields(NavigationPageLoadedEvent $event)
{
$config = [];
$navigationId = $event->getRequest()->get(
'navigationId',
$event->getSalesChannelContext()->getSalesChannel()->getNavigationCategoryId()
);
$category = $this->cmsPageRoute
->load($navigationId, $event->getRequest(), $event->getSalesChannelContext())
->getCategory();
if (!$category) {
return;
}
$customFields = $category->get('customFields');
if (!$customFields) {
return;
}
foreach($customFields as $name => $value) {
if ($name !== $this->customFieldName || empty($value)) {
continue;
}
$config['visualOrder'] = json_decode($value);
}
$event->getContext()->addExtension($this->pluginName, new ArrayEntity($config));
}
}