正如m0c所指出的,该解决方案确实是利用自定义验证约束。然而,我发现 Symfony2.1 中已经存在这样的约束验证器,所以我冒昧地将它移植到 2.0(因为某些接口在 2.1 中显然发生了变化)。
以下是Bernhard Schussek 的 Count.php
移植版本(适用于 2.0)和CountValidator.php
用于计数集合(参见https://github.com/symfony/Validator/tree/master/Constraints)。
计数.php
namespace MyVendor\MyBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\MissingOptionsException;
/**
* @Annotation
*
* @api
*/
class Count extends Constraint
{
public $minMessage = 'This collection should contain {{ limit }} elements or more.';
public $maxMessage = 'This collection should contain {{ limit }} elements or less.';
public $exactMessage = 'This collection should contain exactly {{ limit }} elements.';
public $min;
public $max;
public function __construct($options = null)
{
if (null !== $options && !is_array($options)) {
$options = array(
'min' => $options,
'max' => $options,
);
}
parent::__construct($options);
if (null === $this->min && null === $this->max) {
throw new MissingOptionsException('Either option "min" or "max" must be given for constraint ' . __CLASS__, array('min', 'max'));
}
}
}
CountValidator.php
namespace MyVendor\MyBundle\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
class CountValidator extends ConstraintValidator
{
/**
* {@inheritDoc}
*/
public function isValid($value, Constraint $constraint)
{
if (null === $value) {
return false;
}
if (!is_array($value) && !$value instanceof \Countable) {
throw new UnexpectedTypeException($value, 'array or \Countable');
}
$count = count($value);
if ($constraint->min == $constraint->max
&& $count != $constraint->min) {
$this->setMessage($constraint->exactMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
));
return false;
}
if (null !== $constraint->max && $count > $constraint->max) {
$this->setMessage($constraint->maxMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
));
return false;
}
if (null !== $constraint->min && $count < $constraint->min) {
$this->setMessage($constraint->minMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
));
return false;
}
return true;
}
}