मैं एक कस्टम सत्यापन बाधा उत्पन्न करूंगा जो सरणी में प्रत्येक कुंजी-मूल्य जोड़ी (या केवल तभी कुंजी) पर बाधा लागू करता है। 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);
लगता है कि 'getGraphWalker' को हटा दिया गया है और हटा दिया गया है। – Petah