<?php
namespace Okeonline\KejeLogin\Core\Checkout\Customer\Subscriber;
use Doctrine\DBAL\Connection;
use Okeonline\KejeLogin\Core\Checkout\Customer\Exception\LoginIdentifierNotUniqueException;
use Shopware\Core\Checkout\Customer\CustomerEvents;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\NotFilter;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerEntityWrittenSubscriber implements EventSubscriberInterface
{
protected $systemConfigService;
protected $customerRepository;
protected $connection;
public function __construct(
SystemConfigService $systemConfigService,
EntityRepository $customerRepository,
Connection $connection
)
{
$this->systemConfigService = $systemConfigService;
$this->customerRepository = $customerRepository;
$this->connection = $connection;
}
public static function getSubscribedEvents()
{
return [
CustomerEvents::CUSTOMER_WRITTEN_EVENT => 'customerEntityWritten'
];
}
public function customerEntityWritten(EntityWrittenEvent $event)
{
// check if module is active
if(!$this->systemConfigService->get('OkeonlineKejeLogin.config.active'))
{
return;
}
$identifier = $this->systemConfigService->get('OkeonlineKejeLogin.config.identifier') ?? 'customer.customerNumber';
$namespace = explode('.', $identifier);
$identifier = array_pop($namespace);
foreach($event->getWriteResults() as $writeResult)
{
$writeKey = $writeResult->getPrimaryKey();
// Is there any $identifier key changed? No? Continue
if(!array_key_exists($identifier, $writeResult->getPayload()))
{
continue;
}
$identifierValue = $writeResult->getPayload()[$identifier];
// search repository, where not id, and is $identifier = $identifierValue
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter($identifier, $identifierValue));
$criteria->addFilter(new NotFilter(
NotFilter::CONNECTION_AND,
[
new EqualsFilter('id', $writeKey)
]
));
$result = $this->customerRepository->search($criteria, $event->getContext());
// Other entities with same $identifier?
if($result->getTotal() !== 0)
{
$this->connection->executeQuery(
'UPDATE `customer` SET `'.$this->_decamelize($identifier).'` = "'.$identifierValue.'_notUnique" WHERE `id` = UNHEX(\''.$writeKey.'\');'
);
throw new LoginIdentifierNotUniqueException($identifier, $identifierValue);
}
unset($writeKey, $identifierValue);
}
}
protected function _decamelize($string) {
return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $string));
}
}
?>