特征上的Symfony2回调验证

I want to use callback validation on a trait. For example:

<?php
namespace Vendor\Bundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;

/**
 * @Assert\Callback(methods={"validateReview"}, groups={"review"})
 */
trait ReviewableEntity
{
    //...

    /**
     * @param ExecutionContext $context
     */
    public function validateReview(ExecutionContext $context)
    {

        //...

        $context->addViolationAt('review', 'Review must be valid', [], null);

        //...

    }

    //...

}

But it doesn't seem to work. Anyone know if this is this even possible?

If the annotation is on the trait (and not on the method, which is possible with Symfony 2.4+), the callback validator cannot be used with annotations in a trait.

You must use this method if your version of Symfony2 is older than 2.4:

namespace Vendor\Bundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Mapping\ClassMetadata;

trait ReviewableEntity
{
    //...

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addConstraint(
            new Assert\Callback(
                'validateReview',
                array(
                    'groups' => array('review'),
                )
            )
        );
    }

    /**
     * @param ExecutionContext $context
     */
    public function validateReview(ExecutionContext $context)
    {

        //...

        $context->addViolationAt('review', 'Review must be valid', [], null);

        //...

    }

    //...

}

This is just the normal php way to deal with validators without using annotations or configuration file in XML or YML.

I've found this answer with this google query "github symfony entity trait assert callback" as I was fighting with the same problem. For me the first result was this gihtub page containing code that solve the problem.

I have the same question. Found this one via google ... So: I reproduced the problem. Same here.

Extra bit of information: If you put an @Assert annotation on a property inside the trait, it will work. Just the callbacks do not work.