symfony / symfony-docs

The Symfony documentation
https://symfony.com/doc
Other
2.18k stars 5.13k forks source link

Symfony validator no emphasize on public properties inside Constraint class #20406

Open skyferix opened 6 days ago

skyferix commented 6 days ago

I have written custom validator (SequenceValidator). Validator fails unexpectedly when we call getRegex() method on Sequence constraint object I have written example below:

#[\Attribute(\Attribute::TARGET_PROPERTY)]
class Sequence extends Constraint
{
    public function __construct(private readonly string $regex, mixed $options = null, ?array $groups = null, mixed $payload = null)
    {
        parent::__construct($options, $groups, $payload);
    }

    public function getRegex(): string
    {
        return $this->regex;
    }
}

The strange thing is that it will populate properties once on first run and not on other rounds (For example of HTTP request perspective). It happens only in when environment is set to prod.

The only indication that only public variables are properly used for validator constraint is shown in comment when you use Symfony\Bundle\MakerBundle\MakerBundle and make validator in this case bin/console make:validator SequenceValidator

#[\Attribute(\Attribute::TARGET_PROPERTY)]
class Sequence extends Constraint
{
    /*
     * Any public properties become valid options for the annotation.
     * Then, use these in your validator class.
     */
    public string $message = 'The value "{{ value }}" is not valid.';
}

I would like ether add documentation in symfony documentation directly as warning or add it to App\Validator\Contraint class itself to make sure that developers are using the functionality correctly.

xabbuh commented 2 days ago

I am not sure I understand the issue here. Can you explain it with more details or create a small example application that allows to reproduce?

skyferix commented 1 day ago

Sure, will provide example later this week