<?php declare(strict_types=1);
/*
* (c) shopware AG <info@shopware.com>
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Swag\AmazonPay\Core\EventListeners;
use Shopware\Core\Framework\Api\Context\SalesChannelApiSource;
use Shopware\Core\Framework\Uuid\Uuid;
use Shopware\Core\Framework\Validation\BuildValidationEvent;
use Swag\AmazonPay\Components\Account\AmazonPayAccountServiceInterfaceV2;
use Swag\AmazonPay\Core\Checkout\Customer\Exception\AmazonCustomerRecoveryException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Validator\Constraints\Callback;
/**
* This class is used to prevent customer password recovery creation for Amazon Customers.
* The AmazonCustomerRecoveryException is caught in Swag\AmazonPay\Storefront\Controller\AmazonAuthController::generateAccountRecovery
*/
class CustomerRecoverSubscriber implements EventSubscriberInterface
{
/**
* @var AmazonPayAccountServiceInterfaceV2
*/
private $accountService;
/**
* Annotated as object because 6.4 differs from older shopware versions.
* In 6.4 there is a abstract factory, a cached implementation and an uncached one.
*
* @var object
*/
private $salesChannelContextFactory;
public function __construct(
AmazonPayAccountServiceInterfaceV2 $accountService,
object $salesChannelContextFactory
) {
$this->accountService = $accountService;
$this->salesChannelContextFactory = $salesChannelContextFactory;
}
public static function getSubscribedEvents()
{
return [
'framework.validation.customer.email.recover' => 'onCustomerEmailRecover',
];
}
/**
* @throws AmazonCustomerRecoveryException
*/
public function onCustomerEmailRecover(BuildValidationEvent $event): void
{
$contextSource = $event->getContext()->getSource();
if (!$contextSource instanceof SalesChannelApiSource) {
return;
}
if (!\method_exists($this->salesChannelContextFactory, 'create')) {
return;
}
$salesChannelContext = $this->salesChannelContextFactory->create(Uuid::randomHex(), $contextSource->getSalesChannelId());
$event->getDefinition()->add(
'email',
new Callback(
function (string $email) use ($salesChannelContext): void {
$emailBoundToAmazonAccount = (bool) $this->accountService->getAmazonCustomerIdByEmail(
$email,
$salesChannelContext
);
if (!$emailBoundToAmazonAccount) {
return;
}
throw new AmazonCustomerRecoveryException();
}
)
);
}
}