8000 [Validator] Constraints as php 8 Attributes · Issue #38096 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content
[Validator] Constraints as php 8 Attributes #38096
Closed
@derrabus

Description

@derrabus

Description
Now that we've gained a little experience by implementing the @Route annotation as attribute (#37474), let's talk about another obvious use-case for attributes: validation constraints!

I think, we can have a similar upgrade path as with @Route:

  • Add #[Attribute] to a constraint.
  • Keep the first constructor parameter for compatibility with Doctrine Annotations.
  • Add some more constructor parameters that are meant to be used as named parameters.

The thing is: If we want to go that road, we have to enable the constraints one by one and there's quite a lot of them.

I would volunteer to work on a PR that teaches the validator to read constraints from attributes. After that, we could fan out upgrading the individual constraints to whoever wants to join in.

Example
Status quo, from the documentation:

// src/Entity/Author.php
namespace App\Entity;

// ...
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    /**
     * @Assert\Choice(
     *     choices = { "fiction", "non-fiction" },
     *     message = "Choose a valid genre."
     * )
     */
    private $genre;

    // ...
}

Possible attribute version:

// src/Entity/Author.php
namespace App\Entity;

// ...
use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Choice(
        choices: ['fiction', 'non-fiction'],
        message: 'Choose a valid genre.',
    )]
    private $genre;

    // ...
}

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

      0