<?php
namespace Bidcoz\Bundle\UserBundle\EventListener;
use Bidcoz\Bundle\CoreBundle\Entity\Config;
use Bidcoz\Bundle\UserBundle\PhoneNumberAssociationManager;
use Doctrine\Persistence\ObjectManager;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\UserEvent;
use FOS\UserBundle\FOSUserEvents;
use RS\DiExtraBundle\Annotation as DI;
use Symfony\Component\Security\Core\Security;
/**
* @DI\Service
*/
class UserRegistrationListener
{
const TEST_DOMAIN_REGEX = '/test\.com$/';
private $em;
private $security;
private $config;
private $phoneNumberAssociationManager;
/**
* @DI\InjectParams({
* "em" = @DI\Inject("doctrine.orm.default_entity_manager"),
* "phoneNumberAssociationManager" = @DI\Inject("phone_number_association_manager"),
* "security" = @DI\Inject("security.helper"),
* })
*/
public function __construct(ObjectManager $em, PhoneNumberAssociationManager $phoneNumberAssociationManager, Security $security)
{
$this->em = $em;
$this->security = $security;
$this->phoneNumberAssociationManager = $phoneNumberAssociationManager;
}
/**
* @DI\Observe(FOSUserEvents::REGISTRATION_INITIALIZE)
*/
public function onRegistrationInit(UserEvent $event)
{
$user = $this->security->getUser();
if (!$user) {
$user = $event->getUser();
$user->setUsername(uniqid('', true));
$user->setUserTerms($this->getCurrentTerms());
}
}
/**
* @DI\Observe(FOSUserEvents::REGISTRATION_COMPLETED)
*/
public function onRegistrationComplete(FilterUserResponseEvent $event)
{
$user = $event->getUser();
$user->setLoggedIn();
$email = $user->getEmailCanonical();
if (1 === preg_match(self::TEST_DOMAIN_REGEX, $email)) {
$user->setTest(true);
}
}
/**
* @DI\Observe(FOSUserEvents::REGISTRATION_SUCCESS)
*/
public function onRegistrationSuccess(FormEvent $event)
{
$user = $event->getForm()->getData();
$this->phoneNumberAssociationManager->associateNumbers($user);
}
protected function getCurrentTerms()
{
return $this->getCurrentConfig()->getUserTerms();
}
private function getCurrentConfig()
{
if (!$this->config) {
$this->config = $this->em->getRepository(Config::class)->findActiveConfig();
}
return $this->config;
}
}