<?php
declare(strict_types=1);
namespace Module23ImprovedTax\StoreFrontend\SalesChannel;
use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressDefinition;
use Shopware\Core\Checkout\Customer\Aggregate\CustomerAddress\CustomerAddressEntity;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\DefinitionInstanceRegistry;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
use function assert;
use function dump;
class ImprovedCustomerTax
{
private ImprovedCountryTax $improvedCountryTax;
private DefinitionInstanceRegistry $definitionRegistry;
/**
* @param ImprovedCountryTax $improvedCountryTax
*/
public function __construct(ImprovedCountryTax $improvedCountryTax, DefinitionInstanceRegistry $definitionRegistry)
{
$this->improvedCountryTax = $improvedCountryTax;
$this->definitionRegistry = $definitionRegistry;
}
public function __invoke(EntityLoadedEvent $event): void
{
if (empty($event->getEntities()) || ($event->getContext()->getSource() instanceof AdminApiSource)) {
return;
}
$customer = $event->getEntities()[0];
assert($customer instanceof CustomerEntity);
$definition = $this->definitionRegistry->get(CustomerAddressDefinition::class);
$repository = $this->definitionRegistry->getRepository($definition->getEntityName());
$result = $repository->search(new Criteria([$customer->getDefaultBillingAddressId()]), $event->getContext());
$address = $result->first();
assert($address instanceof CustomerAddressEntity);
$customer->setDefaultBillingAddress($address);
$this->improvedCountryTax->setCustomer($customer);
}
}