mentalic
mentalic

Reputation: 996

Symfony2 redirect all requests

I would like to know if there is a way to redirect all requests if there is a condition. For example, if I have an entity User with websiteDisabled = true. As far as I know, you cannot redirect from a service. Is there any other way?

Upvotes: 1

Views: 2642

Answers (1)

Pete Mitchell
Pete Mitchell

Reputation: 2879

You want to create a listener that listens to the kernel.request event (documentation here). In that listener you have access to the request, and the container so you can do anything you like. During kernel.request Symfony gives you a GetResponseEvent.

You can set a Response object on this event just as you would return a response in a controller. If you do set a response, Symfony will return it and not go through the normal request --> controller --> response cycle.

namespace Acme\UserBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\DependencyInjection\ContainerAware;

class UserRedirectListener extends ContainerAware
{
    public function onKernelRequest(GetResponseEvent $event)
    {
        if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
            // don't do anything if it's not the master request
            return;
        }

        $user = $this->container->get('security.context')->getToken()->getUser();

        // for example...
        if ($user->websiteDisabled === false) {
            return;
        }

        // here you could render a template, or create a RedirectResponse
        // or whatever it is
        $response = new Response();

        // as soon as you call GetResponseEvent#setResponse
        // symfony will stop propogation and return the response
        // no other framework code will be executed
        $event->setResponse($response);
    }
}

You will also need to register the event listener in one of your config files, for example:

# app/config/config.yml
services:
    kernel.listener.your_listener_name:
        class: Acme\UserBundle\EventListener\UserRedirectListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Upvotes: 5

Related Questions