Narrow property types in validated objects

Open
#369 5 comments 10 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
30/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
php, symfony
Domain
devtools

Research direction

Start by reading ObjectType::getProperty(), isSuperTypeOf(), and acceptsWithReason(), then review PHPStan's custom PHPDoc type extension guidance. Investigate how Symfony Validator attributes and the validate() result could be represented, with completion requiring a decided design for validated object types and type narrowing.

Written by the indexing model from the issue text.

Description

/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.

Dominant language
PHP
Stars
800
Forks
104
Avg merge
4m
Merged PRs (30d)
1

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from phpstan/phpstan-symfony

All issues in phpstan/phpstan-symfony

Similar issues

More PHP issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.