<?php
namespace Aqarmap\Bundle\UserBundle\EventListener;
use App\Service\Security\AuthServer;
use Aqarmap\Bundle\ListingBundle\Entity\Phone;
use Aqarmap\Bundle\ListingBundle\Entity\UserPhone;
use Aqarmap\Bundle\UserBundle\Entity\User;
use Aqarmap\Bundle\UserBundle\Model\QuickLead;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class RegistrationSuccessListener implements EventSubscriberInterface
{
private UrlGeneratorInterface $router;
private AuthServer $authServer;
/**
* Create a user subscriber instance.
*/
public function __construct(UrlGeneratorInterface $router, AuthServer $authServer)
{
$this->router = $router;
$this->authServer = $authServer;
}
/**
* Register the listeners for the subscriber.
*/
public static function getSubScribedEvents()
{
return [
FOSUserEvents::REGISTRATION_SUCCESS => [
['onRegistrationFormValidated', 0],
['onRegistrationSuccess', 0],
],
];
}
/**
* Send notification when registration completed.
*/
public function onRegistrationSuccess(FormEvent $event): void
{
$url = $this->router->generate('homepage');
$event->setResponse(new RedirectResponse($url));
}
public function onRegistrationFormValidated(FormEvent $event): void
{
/** @var QuickLead $lead */
$lead = $event->getForm()->getData();
if ($lead instanceof QuickLead) {
$user = new User();
$user->setFullName($lead->getName());
$user->setEmailCanonical($lead->getEmail());
$user->setTempCountryCode($lead->getCountryCode());
$userPhone = new UserPhone();
$userPhone->setUser($user);
$userPhone->setPhone(new Phone($lead->getPhone(), $lead->getCountryCode()));
$userPhone->setMain(true);
$user->addPhone($userPhone);
} else {
/** @var User $user */
$user = $event->getForm()->getData();
}
$this->authServer->register($user);
}
}