Skip to content

Narrow property types in validated objects #369

Open
@ondrejmirtes

Description

@ondrejmirtes

/cc @DaveLiddament

When an object is validated with Symfony Validator, we could narrow down its property types based on constraints.

My idea is:

  • Create class ValidatedObjectType extends ObjectType
  • This class could override ObjectType::getProperty(), read the validator attributes, and narrow the property type in reflection returned from parent. We'd probably create new ValidatedObjectPropertyReflection, inject the original object, and only override the type getters.
  • Also override what ValidatedObjectType::isSuperTypeOf and acceptsWithReason answer.
  • In PHPDocs we could typehint something like symfony-validated<UserDTO> and return ValidatedObjectType thanks to https://phpstan.org/developing-extensions/custom-phpdoc-types.

The only missing part is to narrow the object type to a validated one after calling the validator:

    $errors = $validator->validate($author);
    if (count($errors) === 0) { /* here we have a validated object */ }

This interface isn't really static analysis friendly. It'd be a job for a type-specifying extension to do that, but something like $validator->isValid($author) would be much easier to work with.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions