<?php declare(strict_types=1);
namespace Crehler\MojeBambinoEngine\Subscriber;
use Crehler\Arrangements\CrehlerArrangements;
use Crehler\MojeBambinoEngine\Util\Lifecycle\ActivateDeactivate;
use Shopware\Core\Content\Category\CategoryEntity;
use Shopware\Core\Content\Category\CategoryEvents;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CategoryResultSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CategoryEvents::CATEGORY_LOADED_EVENT => 'onCategoryResult'
];
}
public function onCategoryResult(EntityLoadedEvent $event)
{
try {
if ($event->getContext()->getScope() !== Context::CRUD_API_SCOPE) {
return;
}
/** @var CategoryEntity $category */
foreach ($event->getEntities() as $category) {
$this->initializationCustomFields(ActivateDeactivate::CATEGORY_CUSTOM_FIELDS, $category);
}
} catch (\Throwable $exception) {
dd($exception);
}
}
private function initializationCustomFields(array $customFields, CategoryEntity $category): void
{
$prepareCustomFields = $category->getCustomFields();
foreach ($customFields as $customField) {
if (isset($prepareCustomFields[$customField['name']])
&& $customField['type'] === CustomFieldTypes::BOOL) {
if ($prepareCustomFields[$customField['name']] === '') {
$prepareCustomFields[$customField['name']] = false;
}
if ($prepareCustomFields[$customField['name']] === '1') {
$prepareCustomFields[$customField['name']] = true;
}
}
}
$category->setCustomFields($prepareCustomFields);
}
}