不能对属性或 getter 施加约束

The constraint cannot be put on properties or getters

我尝试在 symfony 3

中创建 custom constraint

我有错误

约束 App\Bundle\MyBundle\Validator\Constraints\Code 不能放在属性或 getter 上

<?php
// vendor/app/mybundle/Validator/Constraints/Code.php

namespace App\Bundle\MyBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;


class Code extends Constraint
{
    public $message = 'Error validate message!!!';
    public function validatedBy()
    {
        return 'alias_name';
    }

    public function getTargets()
    {
      //return self::CLASS_CONSTRAINT; // error "The constraint cannot be put on properties or getters"
      return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT); // working, but $value is a STRING!!!
    }
 }

我的vendor/app/mybundle/Validator/Constraints/CodeValidator.php

<?php
// vendor/app/mybundle/Validator/Constraints/CodeValidator.php

namespace App\Bundle\MyBundle\Validator\Constraints;

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

class CodeValidator extends ConstraintValidator
{
     public function validate($value, Constraint $constraint)
     {
         $value->getId(); // this code not working, because $value is STRING!!
         $this->context->buildViolation($constraint->message)
             ->atPath('code')
             ->addViolation();
     }

}

我哪里弄错了?

您创建了一个只应用于整个实体的约束,例如:

/**
 * @AppAssert\SectionCode
 */
class MyEntity
{
    // ...
}

如果您希望将约束应用于 class 的成员,请完全删除您的 getTargets() 函数。

尝试将此添加到您的约束中:

/**
 * @Annotation
 * @Target({"PROPERTY", "METHOD", "ANNOTATION"})
 */

编辑

今天早上,我花时间尝试了您在全新安装的 symfony 3 上的实现。

此外,如果您在 属性 上添加 @AcmeAssert\Code,如下所示:

use AppBundle\Validator\Constraints as AcmeAssert;

// ...

/**
 * @var string
 * @AcmeAssert\Code
 * @ORM\Column(name="code", type="string")
 */
private $code;

只有字段会被验证,所以$value表示属性的字段值。
例如,如果您在实体中的 $code 属性 上分配 @AcmeAssert\Code,当提交表单时,您的验证器的 $value 将代表您的字段值$code 属性).

如果您在实体顶部添加 @AcmeAssert\Code,如下所示:

use AppBundle\Validator\Constraints as AcmeAssert;

/**
 * Foo
 *
 * @ORM\Table(name="foo")
 * @AcmeAssert\Code
 * @ORM\Entity(repositoryClass="AppBundle\Repository\FooRepository")
 */
class Foo

然后,$value 将代表您的完整实体,您可以使用 getter 进行所需的所有验证。

我已将我的测试项目添加到存储库中,您可以使用它来查看如何使用两个替代方案:sf3-constraint-test

在我的示例中,实体 AppBundle::Bar 对 属性 具有约束,而 AppBundle::Foo 对整个实体具有约束。

希望这是你需要的!

EDIT2

如果您在 yaml 映射中,请使用以下内容对您的整个实体应用约束并通过约束中的 $value 访问完整对象:

AppBundle\Entity\AcmeEntity:
    constraints:
        - App\Bundle\MyBundle\Validator\Constraints\Code: ~

在你的映射之上。

如果您只想对一个 属性 应用约束,并使用 $value 访问字段的值,请保持原样并在 $value 上执行您的逻辑是一个字符串(映射中约束实体 属性 对应的字段值),类似于 :

AppBundle\Entity\AcmeEntity:
    properties:
            # ...
            code:
                - App\Bundle\MyBundle\Validator\Constraints\Code: ~