Skip to content

Validator failing with #[Cascade] and a union type #49629

Closed
@oprypkhantc

Description

@oprypkhantc

Symfony version(s) affected

6.2.7

Description

Hey.

I'm using symfony/validator as a standalone package to validate DTOs that come from frontend. To handle optional values (i.e. those that can be missing from the payload), I use a special MissingValue type in a union with the type I want (see reproduction).

I then use a custom ConstraintValidatorFactory to skip validation of MissingValue values. It all plays out very nicely, but there's one place where symfony/validator is not expecting a union: https://github.com/symfony/validator/blob/6.2/Mapping/ClassMetadata.php#L197

Here $property->getType() returns a ReflectionUnionType, while ReflectionNamedType is expected, so it throws an error for a missing ->getName() method.

How to reproduce

enum MissingValue
{
    case INSTANCE;
}

#[Cascade]
class InputDTO {
    #[Length(min: 1, max: 500)]
    public readonly string|null|MissingValue $optionalField = MissingValue::INSTANCE;
}

$validator->validate(new InputDTO());

Possible Solution

I'm aware my use case is not directly supported by symfony/validator, but this could be an easy fix: remove this check altogether, adding a #[Valid] attribute to every field regardless of it's type.

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