<?php declare(strict_types=1);
/**
* @copyright 2020 Crehler Sp. z o. o. <https://crehler.com>
*
* @author Jakub MedyĆski <jme@crehler.com>
* @support Crehler <support@crehler.com>
* @created 14 sie 2020
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\Inspirations\Subscriber;
use Crehler\Inspirations\CrehlerInspirations;
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)
{
if ($event->getContext()->getScope() !== Context::CRUD_API_SCOPE) {
return;
}
/** @var CategoryEntity $category */
foreach ($event->getEntities() as $category) {
$this->initializationCustomFields(CrehlerInspirations::CATEGORY_CUSTOM_FIELDS, $category);
}
}
private function initializationCustomFields(array $customField, CategoryEntity $category): void
{
$prepareCustomFields = [];
if ($category->getCustomFields() !== null || isset($category->getCustomFields()[$customField['name']])) {
return;
}
if ($customField['type'] === CustomFieldTypes::BOOL) {
$prepareCustomFields[$customField['name']] = false;
} else {
$prepareCustomFields[$customField['name']] = null;
}
$category->setCustomFields($prepareCustomFields);
}
}