Checking if a Symfony route exists

Published on 2022-10-22 • Modified on 2022-10-22

This snippet shows how to check if a Symfony route exists. We mustn't use the getRouteCollection() method because it regenerates the routing cache at every call.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet225Trait
{
    public function snippet225(): void
    {
        // Route that exists
        $route = 'homepage';
        $url = $this->router->generate($route, ['_locale' => 'fr']); // it's the route for /fr and /en
        echo \sprintf("- URL for route \"%s\": \"%s\"\n", $route, $url);

        // Unknown route
        $route = 'foobar';
        try {
            $this->router->generate($route);
        } catch (RouteNotFoundException) {
            echo \sprintf('- Route "%s" bot found!', $route);
        }

        // That's it! 😁
    }
}

 Run this snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  More on Stackoverflow   Read the doc  More on the web

  Work with me!

<?php

declare(strict_types=1);

namespace App\Tests\Integration\Controller\Snippets;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\RouterInterface;

/**
 * @see Snippet225Trait
 */
final class Snippet225Test extends KernelTestCase
{
    private RouterInterface $router;

    protected function setUp(): void
    {
        self::bootKernel();
        $this->router = self::getContainer()->get(RouterInterface::class);
    }

    /**
     * @see Snippet225Trait::snippet225
     */
    public function testSnippet225(): void
    {
        $this->expectException(RouteNotFoundException::class);
        $this->router->generate('foobar');
    }
}