Skip to content

Support custom Symfony Validation Constraint #16

@Kocal

Description

@Kocal

Hello, I'm encountering an issue with custom Validation Constraint.

PhpStan returns me this error:

 ------ ----------------------------------------------------------------------------------- 
  Line   common/Bundle/Common/CoreBundle/Validator/Constraints/IsStringValidator.php        
 ------ ----------------------------------------------------------------------------------- 
  21     Access to an undefined property Symfony\Component\Validator\Constraint::$message.  
 ------ ----------------------------------------------------------------------------------- 

This is my code (just an example, not for production 😄) :

<?php
// packages/common/Bundle/Common/CoreBundle/Validator/Constraints/IsStringValidator.php

declare(strict_types=1);

namespace Yprox\Bundle\Common\CoreBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class IsStringValidator extends ConstraintValidator
{
    /**
     * {@inheritdoc}
     */
    public function validate($value, Constraint $constraint)
    {
        if (null === $value || is_string($value)) {
            return true;
        }

        $this->context->addViolation($constraint->message);

        return false;
    }
}
<?php
// packages/common/Bundle/Common/CoreBundle/Validator/Constraints/IsString.php

declare(strict_types=1);

namespace Yprox\Bundle\Common\CoreBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class IsString extends Constraint
{
    public $message = 'Value must be a string';
}

And this is normal, because there is no property $message on abstrac class Symfony\Component\Validator\Constraint.


I tried to update my code to this:

/**
 * {@inheritdoc}
 */
public function validate($value, IsString $constraint)

but I can't because the declaration is not compatible with ConstraintValidatorInterface::validate($value, Constraint $constraint).

So I tried with a PHPDoc like this:

/**
 * {@inheritdoc}
 * @param IsString $constraint
 */
public function validate($value, Constraint $constraint)

but I still have the same error from PhpStan.


Is there any workaround for that? Should I ignore this error by configuring PhpStan?

Maybe PhpStan can automatically call Constraint#validatedBy()? I'm not sure about that 😕 ...

Thank you! 🙂

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions