<?php
namespace Selfdelve\Cms\Subscriber;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Checkout\Customer\Aggregate\CustomerGroup\CustomerGroupEntity;
use Shopware\Core\Framework\Api\Context\AdminApiSource;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
class CustomerLoadedSubscriber implements EventSubscriberInterface
{
const UNVERIFIED_PATTERN = '***%s***UNVERIFIED***';
private EntityRepositoryInterface $customerRepository;
private EntityRepositoryInterface $customerGroupRepository;
/**
* @param EntityRepositoryInterface $customerRepository
* @param EntityRepositoryInterface $customerGroupRepository
*/
public function __construct(
EntityRepositoryInterface $customerRepository,
EntityRepositoryInterface $customerGroupRepository
)
{
$this->customerRepository = $customerRepository;
$this->customerGroupRepository = $customerGroupRepository;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
CustomerEvents::CUSTOMER_LOADED_EVENT => 'onCustomerLoaded',
];
}
/**
* If a business user requested membership in a business customer group and
* the request is still pending, then mask the given vat ids in order to avoid illegitimate orders.
*
* @param EntityLoadedEvent $event
* @return void
*/
public function onCustomerLoaded(EntityLoadedEvent $event)
{
// Ignore in backend
if ($event->getContext()->getSource() instanceof AdminApiSource) {
return;
}
if (0 === count($event->getEntities())) {
return;
}
foreach ($event->getEntities() as $entity) {
if (!$entity instanceof CustomerEntity || '' === (string) $entity->getRequestedGroupId()) {
continue;
}
/** @var CustomerGroupEntity $customerGroup */
$customerGroup = $this->customerGroupRepository->search(
new Criteria([$entity->getRequestedGroupId()]),
$event->getContext()
)->first();
if (!$customerGroup instanceof CustomerGroupEntity || false === $customerGroup->getRegistrationOnlyCompanyRegistration()) {
continue;
}
// Business customer group requested
$vatIds = $entity->getVatIds();
foreach ($vatIds as &$vatId) {
$vatId = sprintf(self::UNVERIFIED_PATTERN, $vatId);
}
$entity->setVatIds($vatIds);
}
}
}