17

如何使用 Symfony Validation 验证数组键?

假设我有以下内容,并且emails数组的每个键都是一个 ID。如何使用回调或其他一些约束(例如,正则表达式约束而不是回调)来验证它们?

$input = [
    'emails' => [
        7 => 'david@panmedia.co.nz',
        12 => 'some@email.add',
    ],
    'user' => 'bob',
    'amount' => 7,
];

use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints;
$validator = Validation::createValidator();
$constraint = new Constraints\Collection(array(
    'emails' => new Constraints\All(array(
        new Constraints\Email(),
    )),
    'user' => new Constraints\Regex('/[a-z]/i'),
    'amount' => new Constraints\Range(['min' => 5, 'max' => 10]),
));

$violations = $validator->validateValue($input, $constraint);
echo $violations;

(使用最新的 dev-master symfony)

4

4 回答 4

7

我将创建一个自定义验证约束,该约束对数组中的每个键值对(或仅当您想要的键)应用约束。类似于All约束,但验证是在键值对上执行的,而不仅仅是值。

namespace GLS\DemoBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;

class AssocAll extends Constraint
{
    public $constraints = array();

    public function __construct($options = null)
    {
        parent::__construct($options);

        if (! is_array($this->constraints)) {
            $this->constraints = array($this->constraints);
        }

        foreach ($this->constraints as $constraint) {
            if (!$constraint instanceof Constraint) {
                throw new ConstraintDefinitionException('The value ' . $constraint . ' is not an instance of Constraint in constraint ' . __CLASS__);
            }
        }
    }

    public function getDefaultOption()
    {
        return 'constraints';
    }

    public function getRequiredOptions()
    {
        return array('constraints');
    }
}

约束验证器,它将带有键值对的数组传递给每个约束:

namespace GLS\DemooBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;


class AssocAllValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (null === $value) {
            return;
        }

        if (!is_array($value) && !$value instanceof \Traversable) {
            throw new UnexpectedTypeException($value, 'array or Traversable');
        }

        $walker = $this->context->getGraphWalker();
        $group = $this->context->getGroup();
        $propertyPath = $this->context->getPropertyPath();

        foreach ($value as $key => $element) {
            foreach ($constraint->constraints as $constr) {
                $walker->walkConstraint($constr, array($key, $element), $group, $propertyPath.'['.$key.']');
            }
        }
    }
}

我想,只有Callback将约束应用于您放置验证逻辑的每个键值对才有意义。

use GLS\DemoBundle\Validator\Constraints\AssocAll;

$validator = Validation::createValidator();
$constraint = new Constraints\Collection(array(
    'emails' => new AssocAll(array(
        new Constraints\Callback(array(
            'methods' => array(function($item, ExecutionContext $context) {
                    $key = $item[0];
                    $value = $item[1];

                    //your validation logic goes here
                    //...
                }
            ))),
    )),
    'user' => new Constraints\Regex('/^[a-z]+$/i'),
    'amount' => new Constraints\Range(['min' => 5, 'max' => 10]),
));

$violations = $validator->validateValue($input, $constraint);
var_dump($violations);
于 2013-04-23T18:20:58.577 回答
3

有一个回调约束。请参阅http://symfony.com/doc/master/reference/constraints/Callback.html

更新:

我找不到更简洁的方法来获取正在验证的当前值的键。可能有更好的方法,我没有花太多时间在这上面,但它适用于你的情况。

    use Symfony\Component\Validator\Constraints;
    use Symfony\Component\Validator\Context\ExecutionContextInterface;

    // ...

    $input = array(
    'emails' => array(
            7 => 'david@panmedia.co.nz',
            12 => 'some@email.add',
    ),
    'user' => 'bob',
    'amount' => 7,
    );

    // inside a sf2 controller: $validator = $this->get('validator.builder')->getValidator();
    $validator = Validation::createValidator();
    $constraint = new Constraints\Collection(array(
        'emails' => new Constraints\All(array(
                new Constraints\Email(),
                new Constraints\Callback(array('methods' => array(function($value, ExecutionContextInterface $context){
                    $propertyPath = $context->getPropertyPath();
                    $valueKey = preg_replace('/[^0-9]/','',$propertyPath);
                    if($valueKey == 7){
                        $context->addViolationAt('email', sprintf('E-Mail %s Has Has Key 7',$value), array(), null);
                    }
                })))
        )),
        'user' => new Constraints\Regex('/[a-z]/i'),
        'amount' => new Constraints\Range(array('min' => 5, 'max' => 10)),
    ));

    $violations = $validator->validate($input, $constraint);
    echo $violations;
于 2013-04-17T03:45:43.830 回答
-2

您可以使用 php 函数array_flip来反转键、值,并使用验证器或自定义验证器。

希望它有帮助。

最良好的问候。

于 2013-04-20T10:33:01.807 回答
-2

有点晚了,但是给你,我的朋友:

use Symfony\Component\Validator\Constraints as Assert;

public function getConstraints()
{
    return [
        'employee' => [new Assert\NotBlank(), new Assert\Type("integer")],
        'terms' => [new Assert\NotBlank(), new Assert\Type("array")],
        'pivotData' => new Assert\All([
            new Assert\Type("array"),
            new Assert\Collection([
                'amount' => new Assert\Optional(new Assert\Type('double'))
            ])
        ]),
    ];
}

这里有几点需要注意:

  • 在上面提供的示例中,我们正在验证pivotData密钥。pivotData应该是我们要验证的额外数据数组。

  • 每次我们想要验证一个数组时,我们都以 开头new Assert\All,这意味着我们想要验证其中的所有内容pivotData

  • 之后,我们添加 newAssert\Type("array")来检查一个数组是否真的从前端传递过来。

  • 而且,最重要的是,我们创建了一个new Assert\Collection我们一个一个地定义我们的新属性的地方,作为一个标准。在上面的示例中,我添加了一个amount表示 pivotData 属性的键。您可以在这里自由列出您的所有属性,它们将得到验证:)

祝你好运 :)

于 2017-10-13T08:24:29.397 回答