Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Symfony 4 (Flex) redirect event subscriber in replace of psr-7 middleware
<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class AuthenticatedSubscriber
*
* @package App\EventSubscriber
*/
class AuthenticatedSubscriber implements EventSubscriberInterface
{
/**
* @var SessionInterface
*/
protected $session;
/**
* NotAuthenticatedSubscriber constructor.
*
* @param SessionInterface $session
*/
public function __construct(SessionInterface $session)
{
$this->session = $session;
}
/**
* @param FilterControllerEvent $event
*
* @return void
*/
public function onKernelController(FilterControllerEvent $event)
{
$controller = $event->getController();
//ignore
if(!is_array($controller)) return;
if($controller[0] instanceof AuthenticatedSubscriberInterface
&& $this->session->has('user/auth')) {
$event->setController(function() {
return new RedirectResponse('/dashboard');
});
}
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::CONTROLLER => 'onKernelController',
];
}
}
@exts

This comment has been minimized.

Copy link
Owner Author

@exts exts commented Dec 6, 2017

Essentially I needed to replace my authenticated middleware to check if a user is logged in and not authenticated middleware from a psr-7 project so i could either redirect say from the login form to the dashboard or if not logged in to the login form.

Then all I had to do was implement the interface necessary to the controller itself which is pretty neat. You could probably go as far as to do more specific checks for more complex controllers with multiple actions.

//src/EventSubscriber/AuthenticatedSubscriberInterface.php
interface AuthenticatedSubscriberInterface 
{
}

//src/Controllers/LoginController.php
class LoginController implements AuthenticatedSubscriberInterface
{

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment