如何使用 Symfony 验证来验证数组密钥?

2022-08-30 23:45:49

如何使用 Symfony 验证来验证数组密钥?

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

$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;

(使用最新的开发大师符号)


答案 1

我会创建一个自定义验证约束,该约束对数组中的每个键值对(或仅在需要时使用键)应用约束。与约束类似,但验证是对键值对执行的,而不仅仅是值。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);

答案 2

有一个回调约束。查看 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;

推荐