<?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 31 mar 2020
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Crehler\VariantsAdvanced\Subscriber;
use Crehler\MojeBambinoEngine\Service\CrehlerContextService;
use Crehler\VariantsAdvanced\Util\Lifecycle\ActivateDeactivate;
use Shopware\Core\Content\Property\PropertyEvents;
use Shopware\Core\Content\Property\PropertyGroupEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PropertyGroupResultSubscriber implements EventSubscriberInterface
{
private CrehlerContextService $crehlerContextService;
public function __construct(CrehlerContextService $crehlerContextService)
{
$this->crehlerContextService = $crehlerContextService;
}
public static function getSubscribedEvents(): array
{
return [
PropertyEvents::PROPERTY_GROUP_LOADED_EVENT => 'onPropertyGroupLoaded'
];
}
public function onPropertyGroupLoaded(EntityLoadedEvent $event): void
{
if($this->crehlerContextService->get(CrehlerContextService::PRODUCT_EXPORT_GENERATE, false)) return;
/** @var PropertyGroupEntity $propertyGroup */
foreach ($event->getEntities() as $propertyGroup) {
$this->initializationCustomFields(ActivateDeactivate::PROPERTY_GROUP_CUSTOM_FIELDS, $propertyGroup);
}
}
private function initializationCustomFields(array $customFields, PropertyGroupEntity $propertyGroup): void
{
$prepareCustomFields = [];
foreach ($customFields as $customField) {
if ($propertyGroup->getCustomFields() !== null || isset($propertyGroup->getCustomFields()[$customField['name']])) {
return;
}
if ($customField['type'] === CustomFieldTypes::BOOL) {
$prepareCustomFields[$customField['name']] = false;
} else {
$prepareCustomFields[$customField['name']] = null;
}
}
$propertyGroup->setCustomFields($prepareCustomFields);
}
}