Skip to content

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

Closed
@skyferix

Description

@skyferix

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ValidatorhasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions