<?php
declare(strict_types=1);
namespace FourtwosixRegistrationFields\Subscriber;
use FourtwosixRegistrationFields\FourtwosixRegistrationFields;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\Event\DataMappingEvent;
use Shopware\Core\Framework\Validation\DataBag\DataBag;
class CustomerEventsSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
CustomerEvents::MAPPING_ADDRESS_CREATE => 'onUpsertAddress',
CustomerEvents::MAPPING_REGISTER_CUSTOMER => 'onCustomerUpdateMapping',
CustomerEvents::MAPPING_CUSTOMER_PROFILE_SAVE => 'onCustomerUpdateMapping',
CustomerEvents::MAPPING_REGISTER_ADDRESS_BILLING => 'onAddressUpdateMapping',
CustomerEvents::MAPPING_REGISTER_ADDRESS_SHIPPING => 'onAddressUpdateMapping',
];
}
public function onCustomerUpdateMapping(DataMappingEvent $event)
{
$data = $event->getInput();
if ($data->has('billingAddress')) {
$billingAddress = $data->get('billingAddress');
$billingAddress->add([
'customFields' => $this->getCustomFields($billingAddress),
]);
}
if ($data->has('shippingAddress')) {
$shippingAddress = $data->get('shippingAddress');
$shippingAddress->add([
'customFields' => $this->getCustomFields($shippingAddress),
]);
}
}
public function onUpsertAddress(DataMappingEvent $event)
{
$data = $event->getInput();
$address = $event->getOutput();
$address['customFields'] = $this->getCustomFields($data);
$event->setOutput($address);
}
private function getCustomFields(DataBag $data): array
{
return [
FourtwosixRegistrationFields::FISCAL_CODE_ATTRIBUTE_NAME => strtoupper($data->get('fiscalCode') ?? ''),
FourtwosixRegistrationFields::PEC_ADDRESS_ATTRIBUTE_NAME => strtolower($data->get('pecAddress') ?? ''),
FourtwosixRegistrationFields::RECIPIENT_CODE_ATTRIBUTE_NAME => strtoupper($data->get('recipientCode') ?? ''),
FourtwosixRegistrationFields::COMPANY_TYPE_ATTRIBUTE_NAME => $data->get('companyType'),
];
}
public function onAddressUpdateMapping(DataMappingEvent $event)
{
$data = $event->getInput();
$address = $event->getOutput();
if (!$data->has('customFields')) {
return;
}
$customFields = $data->get('customFields');
$address['customFields'] = $customFields;
$event->setOutput($address);
}
}