<?php declare(strict_types=1);
namespace Uandi\UandiEfbLoginById\Subscriber;
use Exception;
use Monolog\Logger;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Uandi\UandiEfbLoginById\Service\EmailSuffixService;
class AccountRecoverySubscriber implements EventSubscriberInterface
{
private EmailSuffixService $emailSuffixService;
private Logger $logger;
/**
* @param EmailSuffixService $emailSuffixService
* @param Logger $logger
*/
public function __construct(
EmailSuffixService $emailSuffixService,
Logger $logger
) {
$this->emailSuffixService = $emailSuffixService;
$this->logger = $logger;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
KernelEvents::CONTROLLER => 'onBeforeGenerateAccountRecovery'
];
}
/**
* Convert customer id to email and perform standard recovery password process
*
* @param ControllerEvent $event
*/
public function onBeforeGenerateAccountRecovery(ControllerEvent $event): void
{
$route = $event->getRequest()->attributes->get('_route') ?? '';
if ($route === 'frontend.account.recover.request') {
try {
$request = $event->getRequest();
//Get email suffix
$emailSuffix = $this->emailSuffixService->getBySalesChannelId(
$request->attributes->get('sw-sales-channel-id', '')
);
//Get email
$customerExternalId = $request->request->get('email') ?? null;
if (is_array($customerExternalId)) {
$customerExternalId = current($customerExternalId);
}
//Check if is not an email and add email suffix
if (strpos($customerExternalId, '@') === false && !empty($customerExternalId)) {
//Update username to use as an email
$request->request->set('email', ['email' => $customerExternalId . $emailSuffix]);
}
} catch (Exception $exception) {
$this->logger->error(
'[onBeforeGenerateAccountRecovery] It was not possible to get username. '
. $exception->getMessage()
);
}
}
}
}