Description
Symfony version(s) affected
6.2, possibly 6.1
Description
When defining routes with enums, the only way to make a default parameter work is by defining it in the #[Route]
attribute. You can't define it in PHP:
#[Route('/nullable/{postEnum}')]
public function enumRouteNullable(?PostEnum $postEnum = null): Response
{
// works without parameter, but no default value
return $this->render('home/enumRoute.html.twig', ['enum' => $postEnum]);
}
#[Route('/default/{postEnum}')]
public function enumRouteDefault(PostEnum $postEnum = PostEnum::VLOG): Response
{
// doesn't compile, `Symfony\Component\Routing\Route cannot contain objects.`
return $this->render('home/enumRoute.html.twig', ['enum' => $postEnum]);
}
#[Route('/default/{postEnum}', defaults: ['postEnum' => PostEnum::VLOG->value])]
public function enumRouteDefaultString(PostEnum $postEnum): Response
{
// works, with proper default value
return $this->render('home/enumRoute.html.twig', ['enum' => $postEnum]);
}
The second solution is the most convenient one, but is not allowed, I get this error: Symfony\Component\Routing\Route cannot contain objects.
(screenshot below)
How to reproduce
I made a test project that crashes accordingly. One controller with the use case, and another controller checking that it's valid with a pure string parameter.
https://github.com/florentdestremau/enum-router-bug
Possible Solution
It goes back to the fact that Backed Enum classes have no __toString() method and this makes the router compiling crash. There is some treatment for route generation that should detect enums and call the ->value
method.