<?php declare(strict_types=1);
namespace GrimmTheme\Storefront\Subscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Customer\Event\CustomerRegisterEvent;
use Shopware\Core\Checkout\Customer\Event\GuestCustomerRegisterEvent;
use GrimmTheme\Service\TaxIdValidator;
class RegistrationSubscriber implements EventSubscriberInterface
{
/**
* @var TaxIdValidator
*/
private $taxIdValidator;
public function __construct(
TaxIdValidator $taxIdValidator
){
$this->taxIdValidator = $taxIdValidator;
}
// for both customer and guest registration, same function executed since guestr registration event extends customer registration event
public static function getSubscribedEvents(): array
{
return [
CustomerRegisterEvent::class => 'onRegisterEvent',
GuestCustomerRegisterEvent::class => 'onRegisterEvent'
];
}
/**
* validates vat against endpoints and updates custom field of customer entity if valid
* sets boolean custom_grimm_customer_tax_free which determines in the TaxDetector, if customer gets VAT free order
*/
public function onRegisterEvent(CustomerRegisterEvent $event)
{
$customer = $event->getCustomer();
$context = $event->getSalesChannelContext();
$billingAddress = $customer->getDefaultBillingAddress();
$billingAddressCountry = $billingAddress->getCountry();
$countryIso = $billingAddressCountry->getIso();
$countryCompanyTaxFree = $billingAddressCountry->getCompanyTax()->getEnabled();
if ($countryIso == "DE" || !$countryCompanyTaxFree || !$customer->getCompany()) {
return;
}
$vatIds = $customer->getVatIds();
if($vatIds && isset($vatIds[0])){
$vatIds = $vatIds[0];
$vatIdValid = $this->taxIdValidator->validateForeignVAT($vatIds, $billingAddress);
if($vatIdValid){
$this->taxIdValidator->setVatValidCustomField($customer, $vatIdValid, $context);
}
}
}
}