Skip to content

[Validator] Encourage type safety #9979

Closed
@kiler129

Description

@kiler129

Example provided at https://symfony.com/doc/current/validation/custom_constraint.html#creating-the-validator-itself shows example validation as:

    public function validate($value, Constraint $constraint)
    {
        if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ string }}', $value)
                ->addViolation();
        }
    }

This is a perfectly fine example, but sets a trap creating assumption that $value is always a string. I think at minimum we should include:

        if (!is_string($value)) {
            throw new UnexpectedTypeException($value, 'string');
        }

if not even something like DateTimeValidator has:

        if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
            throw new UnexpectedTypeException($value, 'string');
        }

        $value = (string) $value;

WDYT?

Metadata

Metadata

Assignees

No one assigned

    Labels

    DXValidatoractionableClear and specific issues ready for anyone to take them.hasPRA Pull Request has already been submitted for this issue.

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions