Description
Q | A |
---|---|
Bug report? | yes |
Feature request? | no |
BC Break report? | no |
RFC? | no |
Symfony version | 3.2 |
For now, if I want to get the User
object in the controller, instead of using $this->getUser()
I'm using typehint in the method's signature, like explained in this article in the blog.
Consider this:
/**
* @Route("/", name="homepage")
*/
public function homepageAction(UserInterface $user)
{
// ...
}
It is possible for me to have no logged-in user. In this case, the $user
will be null but I will have this error:
Controller "AppBundle\Controller\DefaultController::homepageAction()" requires that you provide a value for the "$user" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.
So, in this case, what I need is this:
/**
* @Route("/", name="homepage")
*/
public function homepageAction(UserInterface $user = null)
{
// ...
}
The problem is that, when doing this, the user
property will be automatically added to $request->attributes
, and I'm not expert enough in the core of Symfony to explain why and how to fix it.
I can just presume that it comes from the router compilation process, because I found this in the compiled UrlMatcher:
// var/cache/dev/appDevDebugProjectContainerUrlMatcher.php
// With signature homepageAction(UserInterface $user = null)
// homepage
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'homepage');
}
return array ( 'user' => NULL, '_controller' => 'AppBundle\\Controller\\DefaultController::homepageAction', '_route' => 'homepage',);
}
This means that the compiled route has the user
property whereas it does not have it if I don't set the property as nullable, as seen below:
// var/cache/dev/appDevDebugProjectContainerUrlMatcher.php
// With signature homepageAction(UserInterface $user)
// homepage
if (rtrim($pathinfo, '/') === '') {
if (substr($pathinfo, -1) !== '/') {
return $this->redirect($pathinfo.'/', 'homepage');
}
return array ( '_controller' => 'AppBundle\\Controller\\DefaultController::homepageAction', '_route' => 'homepage',);
}
I tend to think this is a bug: a user should be nullable, because it can already be null when retrieving it from the security.