Skip to content

Dependency Injection Autowiring throws exception for nullable parameters that don't exist #50020

Closed
@radar3301

Description

@radar3301

Symfony version(s) affected

all?

Description

I get a ParameterNotFoundException "You have requested a non-existent parameter "myclass.optional_parameter" with the below code.

ExistentClass $requiredToExist appropriately throws an exception when ExistentClass is not found in the container.
?NonExistentClass $optionalNotExist appropriately is set to null when the NonExistentClass is not found in the container.

I have not tested on any version other than 6.2, so I don't know if this bug exists in other versions.

How to reproduce

namespace App\Service;

class MyServiceClass
{
    public function __construct(
        private ExistentClass $requiredToExist,
        private ?NonExistentClass $optionalNotExist = null,
        #[Autowire('%myclass.optional_parameter%')]
        private ?string $optionalParameter = null,
    ) {}

    public function doStuff()
    {
        if ('value1' == $this->optionalParameter) {
            // do something
        } elseif ('value2' == $this->optionalParameter) {
            // do something else
        }
    }
}

Register App\Service\MyServiceClass as a service, and request it as a parameter to a controller method.

Possible Solution

Naive update to the $attribute instanceof Autowire case of the processAttribute method in Symfony/Component/DependencyInjection/Compiler/AutowirePass.php:

try {
    $value = $this->container->getParameterBag()->resolveValue($attribute->value);
    return $value instanceof Reference && $isOptional ? new Reference($value, ContainerInterface::NULL_ON_INVALID_REFERENCE) : $value;
} catch (ParameterNotFoundException $ex) {
    return $isOptional ? null : throw $ex;
}

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions