<?php
declare(strict_types=1);
namespace FourtwosixRegistrationFields\Subscriber;
use FourtwosixRegistrationFields\FourtwosixRegistrationFields;
use Shopware\Core\Checkout\Cart\Order\CartConvertedEvent;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\Entity;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository as CustomerAddressRepository;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class CartConvertedEventSubscriber implements EventSubscriberInterface
{
private RequestStack $requestStack;
private CustomerAddressRepository $addressRepository;
public function __construct(
RequestStack $requestStack,
CustomerAddressRepository $addressRepository
) {
$this->requestStack = $requestStack;
$this->addressRepository = $addressRepository;
}
public static function getSubscribedEvents(): array
{
return [
CartConvertedEvent::class => 'onCartConvertedEvent',
];
}
public function onCartConvertedEvent(CartConvertedEvent $event): void
{
if (
empty($this->requestStack) ||
empty($request = $this->requestStack->getCurrentRequest())
) {
return;
}
$parameters = $request->request;
if (
!($customer = $event->getSalesChannelContext()->getCustomer()) ||
!($addressBilling = $customer->getActiveBillingAddress()) ||
!($addressShipping = $customer->getActiveShippingAddress())
) {
return;
}
if (
($address = $parameters->get('billingAddress')) &&
($fiscalCode = $address['fiscalCode'])
) {
$this->updateAddress($event->getContext(), $addressBilling, $fiscalCode);
}
if (
($address = $parameters->get('shippingAddress')) &&
($fiscalCode = $address['fiscalCode'])
) {
$this->updateAddress($event->getContext(), $addressShipping, $fiscalCode);
}
}
public function updateAddress(Context $context, Entity &$address, string &$fiscalCode): void
{
$this->addCustomField(
$this->addressRepository,
$context,
$address,
FourtwosixRegistrationFields::FISCAL_CODE_ATTRIBUTE_NAME,
$fiscalCode
);
}
public function addCustomField(
EntityRepository $repository,
Context $context,
Entity $entity,
string $name,
string $value
): void {
$id = $entity->getUniqueIdentifier();
$repository->upsert([[
'id' => $id,
'customFields' => [
$name => $value
]
]], $context);
}
}