断言表达式验证在Symfony 2.4中的属性级别上不起作用

Alb*_*sús 4 validation assert symfony

我正在尝试通过@Assert \ Expression(http://symfony.com/doc/2.4/reference/constraints/Expression.html)在字段级别验证属性。

它可以在以下代码的类级别工作:

/**
 * Foo
 * 
 * @ORM\Table(name="foo")
 * @ORM\HasLifecycleCallbacks()
 * @UniqueEntity("slug")
 * @Assert\Expression(
 *     "this.getPriceFor2PaxStandard() != null or (this.getPriceFor2PaxStandard() == null and !this.isPriceForAccLevelRequired('standard'))",
 *     message="The price for 2 pax standard is required",
 *     groups={"agency_tripEdit_finalsave"}
 * )
 * 
 */
class Foo implements ISpellcheckerLocaleProvider, ProcessStatusAware, DataTransformer
{
Run Code Online (Sandbox Code Playgroud)

但是如果我在属性级别使用相同的代码(应该没问题)不起作用:

/**
     * @var decimal
     *
     * @ORM\Column(name="price_for_2_pax_standard", type="decimal", precision=16, scale=4, nullable=true)
     * @Assert\Expression(
     *     "this.getPriceFor2PaxStandard() != null or (this.getPriceFor2PaxStandard() == null and !this.isPriceForAccLevelRequired('standard'))",
     *     message="The price for 2 pax standard is required",
     *     groups={"agency_tripEdit_finalsave"}
     * )
     */
    private $priceFor2PaxStandard;
Run Code Online (Sandbox Code Playgroud)

另外,如果我使用value代替而不this.getPriceFor2PaxStandard()使用asseriont作为属性级别,则也不起作用。

任何提示将不胜感激:-)

Tom*_*gan 5

这是symfony中的错误。如果查看ExpressionValidator的代码,您会看到它跳过验证值是否为null或空字符串。这对于其他一些约束很有用,但在ExpressionValidator中毫无意义。我刚刚提交了拉动请求以对其进行修复。目前最简单的方法是交换到回调验证器。

<?php

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;

class ExpressionValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof Expression) {
            throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression');
        }

        if (null === $value || '' === $value) {
            return;
        }

        //...
    }

    //...

}
Run Code Online (Sandbox Code Playgroud)