值之间的 Symfony 约束集合

克莱姆米

我正在寻找一种方法来验证通过表单获得的一个数组。

$arr = [13, 64];

该数组由 2 个整数组成,我需要检查这些整数是否介于 0 到 1000 之间,但第二个整数也大于第一个整数,并且差异不能超过 100。我唯一能提出的约束是验证具有已知模式的数字:

'constraints' => new Assert\Collection([
     'fields' => [
           0 => new Assert\Range([
                'min' => 0,
                'max' => 1000,
           ]),
           1 => new Assert\Range([
                'min' => 0,
                'max' => 1000,
           ]),
      ]
 ]),

我的验证中缺少什么:

 $arr = [13, 64]; => should be correct
 $arr = [140, 64]; => not correct, $arr[0] > $arr[1]
 $arr = [13, 340]; => not correct, ($arr[1] - $arr[0]) > 100

我在 symfony 文档中找不到如何验证彼此之间的数组字段,并且不知道是否有办法。

如果有人有小费,欢迎您:)

谢谢你,干杯!

老板

创建自定义表单约束

创建2个文件并将它们放入src/Validator

约束:

// src/Validator/CheckArray.php

namespace App\Validator;

use Symfony\Component\Validator\Constraint;

class CheckArray extends Constraint
{
    public $type = 'One of the values is not an integer.';
    public $range = 'One of the values is not within range. (0 and 1000)';
    public $exceeded = 'Value mismatched. Exceeded expected value.';
}

验证者:

// src/Validator/CheckArrayValidator.php

namespace App\Validator;

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

class CheckArrayValidator extends ConstraintValidator
{
    public function validate($array, Constraint $constraint)
    {
        if (!$constraint instanceof CheckArray) {
            throw new UnexpectedTypeException($constraint, CheckArray::class);
        }

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

        if (!is_array($array)) {
            throw new UnexpectedValueException($array, 'array');
        }

        if ($this->checkType()) {
            $this->context->buildViolation($constraint->type)->addViolation();
        }

        if ($this->checkRange()) {
            $this->context->buildViolation($constraint->range)->addViolation();
        }

        if ($this->checkExceeded()) {
            $this->context->buildViolation($constraint->exceeded)->addViolation();
        }
    }

    private function checkType(array $array): bool
    {
        return $array !== array_filter($array, 'is_int');
    }

    private function checkRange(array $array): bool
    {
        return $array !== array_filter($array, function($v){
            return ($v > 0 && $v < 1000);
        });
    }

    private function checkExceeded(array $array): bool
    {
        if ($array[0] > $array[1]) return true;
        if (($array[1] - $array[0]) > 100) return true;

        return false;
    }
}

在您的表格中:

use App\Validator\CheckArray;

'constraints' => new CheckArray()

未经过全面测试,根据需要调整命名和消息或添加更多内容。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章