How to know allowed methods for one route in Symfony2?

695 Views Asked by At

I'm currently in a listener, and I want to return some headers in my response. $this->router->match($this->request->getPathInfo()); I don't have any information about this. I have however specified the methods :

api_v2_spokespeople_collection:
  path: /spokespeople
  defaults: { _controller: "APIBundle:v2/Spokesperson:getCollection" }
  methods:  [GET, OPTIONS]

Is it finally possible without having to "manually" parse the routing files?

2

There are 2 best solutions below

1
On BEST ANSWER

If you have a route name:

/** @var string $routeName */
/** @var Symfony\Component\HttpFoundation\Request $request */
$routeName = $request->attributes->get('_route');

and you have the @router service (It seems this service was injected into your listener):

// from the controller action.
/** @var Symfony\Bundle\FrameworkBundle\Routing\Router $router */
$router = $this->get('router');

//in your sample should be $this->router directly.

then we can get the route instance and its information through route collection:

/** @var Symfony\Component\Routing\Route $route */
$route = $router->getRouteCollection()->get($routeName);

finally, you need to call to getMethods() to know the defined methods:

/** @var string[] $methods */
$methods = $route->getMethods(); // e.g. array('GET', 'POST')

In one line:

$methods = $this->router->getRouteCollection()->get($request->get('_route'))->getMethods();
4
On

As I understood you are going to get allowed methods for current route. If so then:

$route = $this->request->get('_route');
$methods = $route->getMethods();