Extending Action Argument Resolving

Extending Action Argument Resolving

In the controller guide, you’ve learned that you can get the Symfony\Component\HttpFoundation\Request object via an argument in your controller. This argument has to be type-hinted by the Request class in order to be recognized. This is done via the Symfony\Component\HttpKernel\Controller\ArgumentResolver. By creating and registering custom argument value resolvers, you can extend this functionality.

Built-In Value Resolvers

Symfony ships with the following value resolvers in the HttpKernel component:

Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestAttributeValueResolver

Attempts to find a request attribute that matches the name of the argument.

Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestValueResolver

Injects the current Request if type-hinted with Request or a class extending Request.

Symfony\Component\HttpKernel\Controller\ArgumentResolver\ServiceValueResolver

Injects a service if type-hinted with a valid service class or interface. This works like autowiring.

Symfony\Component\HttpKernel\Controller\ArgumentResolver\SessionValueResolver

Injects the configured session class implementing SessionInterface if type-hinted with SessionInterface or a class implementing SessionInterface.

Symfony\Component\HttpKernel\Controller\ArgumentResolver\DefaultValueResolver

Will set the default value of the argument if present and the argument is optional.

Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver

Verifies if the request data is an array and will add all of them to the argument list. When the action is called, the last (variadic) argument will contain all the values of this array.

In addition, some components and official bundles provide other value resolvers:

Symfony\Component\Security\Http\Controller\UserValueResolver

Injects the object that represents the current logged in user if type-hinted with UserInterface. Default value can be set to null in case the controller can be accessed by anonymous users. It requires installing the Security component.

Symfony\Bundle\SecurityBundle\SecurityUserValueResolver

Injects the object that represents the current logged in user if type-hinted with UserInterface. Default value can be set to null in case the controller can be accessed by anonymous users. It requires installing the SecurityBundle.

Deprecated since version 4.1: The SecurityUserValueResolver was deprecated in Symfony 4.1 in favor of Symfony\Component\Security\Http\Controller\UserValueResolver.

Psr7ServerRequestResolver

Injects a PSR-7 compliant version of the current request if type-hinted with RequestInterface, MessageInterface or ServerRequestInterface. It requires installing the SensioFrameworkExtraBundle.

Adding a Custom Value Resolver

In the next example, you’ll create a value resolver to inject the object that represents the current user whenever a controller method type-hints an argument with the User class:

  1. // src/Controller/UserController.php
  2. namespace App\Controller;
  3. use App\Entity\User;
  4. use Symfony\Component\HttpFoundation\Response;
  5. class UserController
  6. {
  7. public function index(User $user)
  8. {
  9. return new Response('Hello '.$user->getUsername().'!');
  10. }
  11. }

Beware that this feature is already provided by the @ParamConverter annotation from the SensioFrameworkExtraBundle. If you have that bundle installed in your project, add this config to disable the auto-conversion of type-hinted method arguments:

  • YAML

    1. # config/packages/sensio_framework_extra.yaml
    2. sensio_framework_extra:
    3. request:
    4. converters: true
    5. auto_convert: false
  • XML

    1. <!-- config/packages/sensio_framework_extra.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xmlns:sensio-framework-extra="http://symfony.com/schema/dic/symfony_extra"
    6. xsi:schemaLocation="http://symfony.com/schema/dic/services
    7. https://symfony.com/schema/dic/services/services-1.0.xsd
    8. http://symfony.com/schema/dic/symfony_extra
    9. https://symfony.com/schema/dic/symfony_extra/symfony_extra-1.0.xsd">
    10. <sensio-framework-extra:config>
    11. <request converters="true" auto-convert="false"/>
    12. </sensio-framework-extra:config>
    13. </container>
  • PHP

    1. // config/packages/sensio_framework_extra.php
    2. $container->loadFromExtension('sensio_framework_extra', [
    3. 'request' => [
    4. 'converters' => true,
    5. 'auto_convert' => false,
    6. ],
    7. ]);

Adding a new value resolver requires creating a class that implements Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface and defining a service for it. The interface defines two methods:

supports()

This method is used to check whether the value resolver supports the given argument. resolve() will only be called when this returns true.

resolve()

This method will resolve the actual value for the argument. Once the value is resolved, you must yield the value to the ArgumentResolver.

Both methods get the Request object, which is the current request, and an Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata instance. This object contains all information retrieved from the method signature for the current argument.

Now that you know what to do, you can implement this interface. To get the current User, you need the current security token. This token can be retrieved from the token storage:

  1. // src/ArgumentResolver/UserValueResolver.php
  2. namespace App\ArgumentResolver;
  3. use App\Entity\User;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
  6. use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
  7. use Symfony\Component\Security\Core\Security;
  8. class UserValueResolver implements ArgumentValueResolverInterface
  9. {
  10. private $security;
  11. public function __construct(Security $security)
  12. {
  13. $this->security = $security;
  14. }
  15. public function supports(Request $request, ArgumentMetadata $argument)
  16. {
  17. if (User::class !== $argument->getType()) {
  18. return false;
  19. }
  20. return $this->security->getUser() instanceof User;
  21. }
  22. public function resolve(Request $request, ArgumentMetadata $argument)
  23. {
  24. yield $this->security->getUser();
  25. }
  26. }

In order to get the actual User object in your argument, the given value must fulfill the following requirements:

  • An argument must be type-hinted as User in your action method signature;
  • The value must be an instance of the User class.

When all those requirements are met and true is returned, the ArgumentResolver calls resolve() with the same values as it called supports().

That’s it! Now all you have to do is add the configuration for the service container. This can be done by tagging the service with controller.argument_value_resolver and adding a priority.

  • YAML

    1. # config/services.yaml
    2. services:
    3. _defaults:
    4. # ... be sure autowiring is enabled
    5. autowire: true
    6. # ...
    7. App\ArgumentResolver\UserValueResolver:
    8. tags:
    9. - { name: controller.argument_value_resolver, priority: 50 }
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-Instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <!-- ... be sure autowiring is enabled -->
    9. <defaults autowire="true"/>
    10. <!-- ... -->
    11. <service id="App\ArgumentResolver\UserValueResolver">
    12. <tag name="controller.argument_value_resolver" priority="50"/>
    13. </service>
    14. </services>
    15. </container>
  • PHP

    1. // config/services.php
    2. use App\ArgumentResolver\UserValueResolver;
    3. $container->autowire(UserValueResolver::class)
    4. ->addTag('controller.argument_value_resolver', ['priority' => 50])
    5. ;

While adding a priority is optional, it’s recommended to add one to make sure the expected value is injected. The built-in RequestAttributeValueResolver, which fetches attributes from the Request, has a priority of 100. If your resolver also fetches Request attributes, set a priority of 100 or more. Otherwise, set a priority lower than 100 to make sure the argument resolver is not triggered when the Request attribute is present (for example, when passing the user along sub-requests).

Tip

As you can see in the UserValueResolver::supports() method, the user may not be available (e.g. when the controller is not behind a firewall). In these cases, the resolver will not be executed. If no argument value is resolved, an exception will be thrown.

To prevent this, you can add a default value in the controller (e.g. User $user = null). The DefaultValueResolver is executed as the last resolver and will use the default value if no value was already resolved.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.