Skip to content

[DI] Validate constructor arguments #31882

@fancyweb

Description

@fancyweb

Description
I often myself manually validating computed arguments in Compiler Pass.

Example :

$content = Yaml::parseFile('/foo');
if (!is_array($content)) {
    throw new \RuntimeException();
}

if (8 < count($content)) {
    throw new \RuntimeException();
}

$container->getDefinition('foo')->setArgument(0, $content);

Wouldn't it be great if we could enforce strict rules on services arguments (thanks to the Validator component) that would be checked just before compile time to fail properly if there are violations?

That could also prevent us from overriding arguments with invalid values (unless you delete the validation too I guess).

Example
Many implementations possible, something like this for example :

services:
    App\Foo:
        arguments:
            -
                # only constraints (value set later)
                constraints:
                    - Type:
                        type: "array"
                    - Count:
                           max: 8
            - "foo" # only value shortcut (current behavior)
            -
                value: "foo" # only value
            -
                value: "bar" # value + constraints
                constraints:
                    # ...

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