<?php declare(strict_types=1);
namespace Crehler\MojeBambinoEngine\Subscriber;
use Crehler\MojeBambinoEngine\Util\Lifecycle\ActivateDeactivate;
use Shopware\Core\Checkout\Payment\PaymentMethodEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\System\CustomField\CustomFieldTypes;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class PaymentMethodSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
'payment_method.loaded' => 'onPaymentMethodLoaded'
];
}
public function onPaymentMethodLoaded(EntityLoadedEvent $event)
{
if ($event->getContext()->getScope() !== Context::CRUD_API_SCOPE) {
return;
}
/** @var PaymentMethodEntity $paymentMethod */
foreach ($event->getEntities() as $paymentMethod) {
$this->initializationCustomFields(ActivateDeactivate::PAYMENT_METHOD_CUSTOM_FIELDS, $paymentMethod);
}
}
private function initializationCustomFields(array $customFields, PaymentMethodEntity $paymentMethod): void
{
$prepareCustomFields = [];
if ($paymentMethod->getCustomFields() !== null
|| ($paymentMethod->getCustomFields() !== null && isset($paymentMethod->getCustomFields()[$customField['name']]))) {
return;
}
foreach ($customFields as $customField) {
if ($customField['type'] === CustomFieldTypes::BOOL) {
$prepareCustomFields[$customField['name']] = false;
} else {
$prepareCustomFields[$customField['name']] = null;
}
}
$paymentMethod->setCustomFields($prepareCustomFields);
}
}