<?php
namespace App\EventListener;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
// use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
// use Doctrine\Common\Persistence\ObjectManager;
// use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Twig\Environment as Twig_Environment;
/**
* Listener responsible to change datas on register user
*/
class RegistrationListener implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var Twig_Environment
*/
protected $twig;
/**
* @var UrlGeneratorInterface
*/
protected $router;
/**
* RegistrationListener constructor.
*
* @param ContainerInterface $container
* @param \Twig_Environment $twig
* @param UrlGeneratorInterface $router
*/
public function __construct(ContainerInterface $container, Twig_Environment $twig, UrlGeneratorInterface $router)
{
$this->container = $container;
$this->twig = $twig;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInitialize',
FOSUserEvents::REGISTRATION_FAILURE => 'onRegistrationFailure',
FOSUserEvents::REGISTRATION_SUCCESS => ['onRegistrationSuccess', -10],
);
}
public function onRegistrationInitialize(GetResponseUserEvent $event)
{
$currentRoute = $event->getRequest()->attributes->get('_route');
// dump($currentRoute);
if ($currentRoute === "alumni_registration_register") {
$user = $event->getUser();
$user->addRole('ROLE_ALUMNI');
//dump($user);
// $this->twig->addGlobal('form_errors', []);
// dump("alumni");
} else if ($currentRoute === "annonce_registration_register") {
$user = $event->getUser();
$user->addRole('ROLE_ANNO');
}
//die;
}
public function onRegistrationFailure(FormEvent $event)
{
$currentRoute = $event->getRequest()->attributes->get('_route');
if ($this->isRoutesAvailable($currentRoute)) {
$this->twig->addGlobal('form_errors', $event->getForm()->getErrors(true));
}
}
public function onRegistrationSuccess(FormEvent $event)
{
$currentRoute = $event->getRequest()->attributes->get('_route');
if ($this->isRoutesAvailable($currentRoute)) {
$url = $this->router->generate('alumni_profile');
$event->setResponse(new RedirectResponse($url));
} else if ($currentRoute === "annonce_registration_register") {
$url = $this->router->generate('annonce_index');
$event->setResponse(new RedirectResponse($url));
}
}
private function isRoutesAvailable($currentRoute)
{
return in_array(
$currentRoute,
['alumni_registration_register']
);
}
}