<?php declare(strict_types=1);
namespace ThemeOkeOnline\Core\Framework\DatabaseAbstractionLayer;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityIdSearchResultLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntitySearchResultLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EntityLoadedEventSubscriber implements EventSubscriberInterface
{
const DEFAULT_HIGH_PRIORITY = 1000;
public static function getSubscribedEvents(): array
{
$return = [];
/**** OkeonlineProjects ****/
if(class_exists('Okeonline\Projects\Content\Project\ProjectDefinition'))
$return = array_merge($return, ['oo_project_category.loaded' => ['addCustomFieldsStructOnEntityLoaded', self::DEFAULT_HIGH_PRIORITY]]);
if(class_exists('Okeonline\Projects\Content\ProjectCategory\ProjectCategoryDefinition'))
$return = array_merge($return, ['oo_project_category.loaded' => ['addCustomFieldsStructOnEntityLoaded', self::DEFAULT_HIGH_PRIORITY]]);
/**** Shopware Defaults ****/
return array_merge($return, [
'category.loaded' => ['addCustomFieldsStructOnEntityLoaded', self::DEFAULT_HIGH_PRIORITY],
'product.loaded' => ['addCustomFieldsStructOnEntityLoaded', self::DEFAULT_HIGH_PRIORITY],
]);
}
public function addCustomFieldsStructOnEntityLoaded(EntityLoadedEvent $event)
{
// if no array, return directly
if( ! is_array($event->getEntities()))
return;
// loop trought array
foreach($event->getEntities() as $entity)
{
// if there are no custom fields, continue;
if( ! $this->customFieldsExists($entity))
continue;
// if there is already a cf-struct set, continue;
if($entity->hasExtension('cf'))
continue;
$customFields = $entity->getCustomFields();
// add cf-struct, even if customFields is null so it is always available (see struct for details)
$entity->cf = new CustomFieldsStruct($customFields);
}
}
private function customFieldsExists($entity): bool
{
return method_exists($entity, 'getCustomFields');
}
}