2

I build a kernel listener some time ago, to redirect a user to a certain language.

There are several pages, that do not have a translation and where the user should not be redirected. As i use JMSI18nRoutingBundle, i figured, it would be the best way to use the 'options: { i18n: false }' setting from the bundle.

I would need to be able to read the options of the current route inside my kernel listener. It this possible?

Community
  • 1
  • 1
madc
  • 1,674
  • 2
  • 26
  • 41

1 Answers1

4

For getting route options first you will have to get route collection and from route collection you will have to get the route object depending on the route name.

So your listener will have a dependency on router. Your constructor will look some what like this.

/**
 * @var $routeCollection \Symfony\Component\Routing\RouteCollection
 */
private $_routeCollection;

function __construct(\Symfony\Bundle\FrameworkBundle\Routing\Router $router)
{
    $this->_routeCollection = $router->getRouteCollection();
}

Now inside your listener method you will need request object to get current route name. For example if your listener method is onKernelController()

function onKernelController(FilterControllerEvent $event)
{
    /**
     * @var $route \Symfony\Component\Routing\Route
     */
    $route = $this->_routeCollection->get($event->getRequest()->get('_route'));

    // @var $allOptions will have all the options for current route.
    $allOptions = $route->getOptions();

    // To get specific option you can use getOption()
    $someSpecificOption = $route->getOption('<key>');
}
aditya
  • 996
  • 2
  • 12
  • 25
  • Hi, your answer seems to be what I need, but I have an error `__construct()" references class "Symfony\Component\Routing\Router" but no such service exists`. I suppose I forgot to define something somewhere but I don't know what (Note: I'm using Symfony 4). – Asenar Jul 18 '19 at 12:54
  • This solution was proposed for Symfony 2. The framework wen through several major changes to its logic and inner workings, so this will most certainly not work for Symfony 4 anymore. – madc Mar 20 '20 at 08:21