Tester si une route Symfony existe

Publié le 22/10/2022 • Actualisé le 22/10/2022


English language detected! 🇬🇧

  We noticed that your browser is using English. Do you want to read this post in this language?

Read the english version 🇬🇧 Close

Dans ce bout de code, nous voyons comment tester si une route Symfony existe. On ne doit pas utiliser la méthode getRouteCollection() car elle déclenche la régénération du cache de routage à chaque appel.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\Routing\Exception\RouteNotFoundException;

/**
 * J'utilise un trait PHP afin d'isoler chaque snippet dans un fichier.
 * Ce code doit être apellé d'un contrôleur Symfony étendant AbstractController (depuis Symfony 4.2)
 * ou Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Les services sont injectés dans le constructeur du contrôleur principal.
 */
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! 😁
    }
}

 Exécuter le snippet  ≪ this.showUnitTest ? this.trans.hide_unit_test : this.trans.show_unit_test ≫  Plus sur Stackoverflow   Lire la doc  Plus sur le web

  Travaillez avec moi !

<?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');
    }
}