How to get list of all routes of a controller in Symfony2?

SymfonyIndexingControllerRoutesSymfony 2.1

Symfony Problem Overview


I have a controller which implements all routes/URL(s). I had the idea to offer a generic index over all help-pages.

Is there a way to get all routes defined by a controller (from within a controller) in Symfony2?

Symfony Solutions


Solution 1 - Symfony

What you can do is use the cmd with (up to SF2.6)

php app/console router:debug

With SF 2.7 the command is

php app/console debug:router

With SF 3.0 the command is

php bin/console debug:router

which shows you all routes.

If you define a prefix per controller (which I recommend) you could for example use

php app/console router:debug | grep "<prefixhere>"

to display all matching routes

To display get all your routes in the controller, with basically the same output I'd use the following within a controller (it is the same approach used in the router:debug command in the symfony component)

/**
 * @Route("/routes", name="routes")
 * @Method("GET")
 * @Template("routes.html.twig")
 *
 * @return array
 */
public function routeAction()
{
    /** @var Router $router */
    $router = $this->get('router');
    $routes = $router->getRouteCollection();

    foreach ($routes as $route) {
        $this->convertController($route);
    }

    return [
        'routes' => $routes
    ];
}


private function convertController(\Symfony\Component\Routing\Route $route)
{
    $nameParser = $this->get('controller_name_converter');
    if ($route->hasDefault('_controller')) {
        try {
            $route->setDefault('_controller', $nameParser->build($route->getDefault('_controller')));
        } catch (\InvalidArgumentException $e) {
        }
    }
}

routes.html.twig

<table>
{% for route in routes %}
    <tr>
        <td>{{ route.path }}</td>
        <td>{{ route.methods|length > 0 ? route.methods|join(', ') : 'ANY' }}</td>
        <td>{{ route.defaults._controller }}</td>
    </tr>
{% endfor %}
</table>

Output will be:

/_wdt/{token} ANY web_profiler.controller.profiler:toolbarAction etc.

Solution 2 - Symfony

You could get all of the routes, then create an array from that and then pass the routes for that controller to your twig.

It's not a pretty way but it works.. for 2.1 anyways..

    /** @var $router \Symfony\Component\Routing\Router */
    $router = $this->container->get('router');
    /** @var $collection \Symfony\Component\Routing\RouteCollection */
    $collection = $router->getRouteCollection();
    $allRoutes = $collection->all();

    $routes = array();

    /** @var $params \Symfony\Component\Routing\Route */
    foreach ($allRoutes as $route => $params)
    {
        $defaults = $params->getDefaults();

        if (isset($defaults['_controller']))
        {
            $controllerAction = explode(':', $defaults['_controller']);
            $controller = $controllerAction[0];
            
            if (!isset($routes[$controller])) {
                $routes[$controller] = array();
            }

            $routes[$controller][]= $route;
        }
    }

    $thisRoutes = isset($routes[get_class($this)]) ?
                                $routes[get_class($this)] : null ;

Solution 3 - Symfony

I was looking to do just that and after searching the code, I came up with this solution which works for a single controller (or any ressource actually). Works on Symfony 2.4 (I did not test with previous versions) :

$routeCollection = $this->get('routing.loader')->load('\Path\To\Controller\Class');
    
foreach ($routeCollection->all() as $routeName => $route) {
   //do stuff with Route (Symfony\Component\Routing\Route)
}

Solution 4 - Symfony

If anyone is stumbling on this issue, this is how I exported the routes in the global twig scope (symfony 4).

src/Helper/Route.php
<?php

namespace App\Helper;

use Symfony\Component\Routing\RouterInterface;

class Routes
{
    private $routes = [];

    public function __construct(RouterInterface $router)
    {
        foreach ($router->getRouteCollection()->all() as $route_name => $route) {
            $this->routes[$route_name] = $route->getPath();
        }
    }

    public function getRoutes(): array
    {
        return $this->routes;
    }
}
src/config/packages/twig.yaml
twig:
    globals:
        route_paths: '@App\Helper\Routes'

 

Then in your twig file to populate a javascript variable to use in your scripts
<script>
    var Routes = {
        {% for route_name, route_path in routes_service.routes %}
            {{ route_name }}: '{{ route_path }}',
        {% endfor %}
    }
</script>

Solution 5 - Symfony

In Symfony 4 i wanted to get all the routes including controller and actions in one list. In rails you can get this by default.

In Symfony you need to add the parameter show-controllers to the debug:router command.

If somebody looking for the same feature it can be get with:

bin/console debug:router --show-controllers

this will produce a list like the following

------------------------------------------------------------------------- -------------------------------------
Name                   Method    Scheme    Host     Path                    Controller
------------------------------------------------------------------------- -------------------------------------
app_some_good_name     ANY       ANY       ANY      /example/example        ExampleBundle:Example:getExample
------------------------------------------------------------------------- -------------------------------------

Solution 6 - Symfony

The safest way to proceed is to use the symfony controller resolver, because you never know if your controller is defined as a fully qualified class name, a service, or whatever callable declaration.

    foreach ($this->get('router')->getRouteCollection() as $route) {
        $request = new Request();
        $request->attributes->add($route->getDefaults());

        [$service, $method] = $this->resolver->getController($request);

        // Do whatever you like with the instanciated controller
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSammyView Question on Stackoverflow
Solution 1 - SymfonyDerStoffelView Answer on Stackoverflow
Solution 2 - SymfonyqooplmaoView Answer on Stackoverflow
Solution 3 - SymfonyyancgView Answer on Stackoverflow
Solution 4 - SymfonyC AlexView Answer on Stackoverflow
Solution 5 - SymfonyrobView Answer on Stackoverflow
Solution 6 - SymfonyAlain TiembloView Answer on Stackoverflow