Symfony验证程序在无效的Collection上抛出异常

时间:2017-03-01 13:07:30

标签: php validation symfony

当我尝试使用Collection约束验证标量时,symfony验证器会抛出异常。我希望它能够返回违规行为。

示例代码:

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Collection;

$validator = Validation::createValidator();

$input = 'testtesttest';
$constraints = [
    new Collection([
        'fields' => [
            'one' => new Length(array('min' => 10))
        ]
    ])
];

$violationList = $validator->validate($input, $constraints);

引发

PHP Fatal error:  Uncaught Symfony\Component\Validator\Exception\UnexpectedTypeException: Expected argument of type "array or Traversable and ArrayAccess", "string" given in vendor/symfony/validator/Constraints/CollectionValidator.php:37

我在这里做错了吗?

对于其他Constraint类(例如NotBlank,Type),验证程序在遇到无效内容时会添加到违规列表中。在集合的情况下让它抛出异常对我来说似乎很奇怪。我做了一件明显不对的事吗?

2 个答案:

答案 0 :(得分:1)

很抱歉一年后做出答复,但我也遇到了同样的问题。

对我来说,解决方案是创建一个custom Validation Constraint

首先,您必须创建一个自定义约束:CustomCollection,它将包含以下代码(请注意,我的类正在扩展Collection constraint而不是默认的Constraint类):

<?php

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraints\Collection;

class CustomCollection extends Collection
{
    public $message = 'You must provide an array.';
}

然后,您必须实现自定义约束的逻辑(在这种情况下,请验证您的值是一个有效的数组):

<?php

namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\CollectionValidator;

class CustomCollectionValidator extends CollectionValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!\is_array($value)) {
            $this->context->buildViolation($constraint->message)
                ->addViolation();
            return;
        }
        parent::validate($value, $constraint);
    }
}

现在,以我的代码为例,您必须将约束从Collection更改为CustomCollection才能得到违规:

$input = 'testtesttest';
$constraints = [
    new CustomCollection([
        'fields' => [
            'one' => new Length(array('min' => 10))
        ]
    ])
];

$violationList = $validator->validate($input, $constraints);

答案 1 :(得分:0)

您滥用Collection约束。此约束用于验证集合(例如,数组,可遍历对象)。

您应该将一组约束传递给validate方法。

E.g:

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Length;

$validator = Validation::createValidator();

$input = 'testtesttest';
$constraints = [
    new Length(array('min' => 10)),
    // ... And other constraints
];

$violationList = $validator->validate($input, $constraints);

您可以在此处查看有关验证程序的更多信息:https://symfony.com/doc/current/components/validator.html#usage