Last active
December 6, 2017 20:10
-
-
Save exts/91120f967a3810567e2b22693fb179dd to your computer and use it in GitHub Desktop.
Symfony 4 (Flex) redirect event subscriber in replace of psr-7 middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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', | |
]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.