2

I'm trying to create a custom validation constraint, this is the relevant code:

ValidCoupon.php

<?php
namespace Bcg\UtilsBundle\Validator\Constraints;

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


/**
 * @Annotation
 */
class ValidCoupon extends Constraint
{
    public function validatedBy()
    {
        return 'valid_coupon';
    }
    public $message = 'The coupon is not valid.';
}

class ValidCouponValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        var_dump($value);
        if (true) {
            $this->context->addViolation(
                $constraint->message,
                array()
            );
        }
    }
}

I call the service in the config.yml like this:

services:
    validator.unique.valid_coupon:
        class: Bcg\UtilsBundle\Validator\Constraints\ValidCoupon
        tags:
            - { name: validator.constraint_validator, alias: valid_coupon }

The validation.yml looks like this:

Bcg\UtilsBundle\Entity\Order:
    properties:
        coupon:
            - Bcg\UtilsBundle\Validator\Constraints\ValidCoupon: ~

And the error I get is the following:

Expected argument of type "Symfony\Component\Validator\ConstraintValidatorInterface", "Bcg\UtilsBundle\Validator\Constraints\ValidCoupon" given 500 Internal Server Error - UnexpectedTypeException

Full stack trace here.

I'm pretty stuck, it doesn't seem to find ValidCouponValidator I don't really know how to continue from here, I know that the public function validateBy() is executed, so it should be correctly overridden but it doesn't seem so...

1 Answer 1

6

Seems like you have a type in your validator service configuration :

You declare your ValidCoupon class as a validator instead of your ValidCouponValidator (which indeed implements the ConstraintValidatorInterface as the error complains about).

Try this:

services:
    validator.unique.valid_coupon:
        class: Bcg\UtilsBundle\Validator\Constraints\ValidCouponValidator
        tags:
            - { name: validator.constraint_validator, alias: valid_coupon }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I had tried this but the combination of other error prevented me from noticing if this is the correct solution, thanks! I will test a little more but this seems right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.