[Validator] Removed legacy validator classes

This commit is contained in:
Bernhard Schussek 2014-08-06 15:23:29 +02:00
parent fba2393297
commit e844ed0fb5
29 changed files with 242 additions and 904 deletions

View File

@ -718,7 +718,6 @@ class FrameworkExtension extends Extension
switch ($config['api']) {
case '2.4':
$api = Validation::API_VERSION_2_4;
$container->setParameter('validator.validator_factory.class', $container->getParameter('validator.legacy_validator_factory.class'));
break;
case '2.5':
$api = Validation::API_VERSION_2_5;

View File

@ -11,7 +11,6 @@
<parameter key="validator.mapping.cache.apc.class">Symfony\Component\Validator\Mapping\Cache\ApcCache</parameter>
<parameter key="validator.mapping.cache.prefix" />
<parameter key="validator.validator_factory.class">Symfony\Bundle\FrameworkBundle\Validator\ConstraintValidatorFactory</parameter>
<parameter key="validator.legacy_validator_factory.class">Symfony\Bundle\FrameworkBundle\Validator\LegacyConstraintValidatorFactory</parameter>
<parameter key="validator.expression.class">Symfony\Component\Validator\Constraints\ExpressionValidator</parameter>
<parameter key="validator.email.class">Symfony\Component\Validator\Constraints\EmailValidator</parameter>
</parameters>

View File

@ -1,95 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Validator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidatorFactoryInterface;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* Like {@link ConstraintValidatorFactory}, but aware of services compatible
* with the 2.4 API.
*
* @author Bernhard Schussek <bschussek@gmail.com>
* @author Kris Wallsmith <kris@symfony.com>
*
* @see ConstraintValidatorFactory
*/
class LegacyConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
{
const BASE_NAMESPACE = 'Symfony\\Component\\Validator\\Constraints';
const FORM_BASE_NAMESPACE = 'Symfony\\Component\\Form\\Extension\\Validator\\Constraints';
protected $container;
protected $validators;
/**
* Constructor.
*
* @param ContainerInterface $container The service container
* @param array $validators An array of validators
*/
public function __construct(ContainerInterface $container, array $validators = array())
{
$this->container = $container;
$this->validators = $validators;
}
/**
* Returns the validator for the supplied constraint.
*
* @param Constraint $constraint A constraint
*
* @return ConstraintValidatorInterface A validator for the supplied constraint
*
* @throws UnexpectedTypeException When the validator is not an instance of ConstraintValidatorInterface
*/
public function getInstance(Constraint $constraint)
{
$name = $constraint->validatedBy();
if (!isset($this->validators[$name])) {
switch (get_class($constraint)) {
case self::BASE_NAMESPACE.'\\All':
$name = self::BASE_NAMESPACE.'\\LegacyAllValidator';
break;
case self::BASE_NAMESPACE.'\\Choice':
$name = self::BASE_NAMESPACE.'\\LegacyChoiceValidator';
break;
case self::BASE_NAMESPACE.'\\Collection':
$name = self::BASE_NAMESPACE.'\\LegacyCollectionValidator';
break;
case self::BASE_NAMESPACE.'\\Count':
$name = self::BASE_NAMESPACE.'\\LegacyCountValidator';
break;
case self::BASE_NAMESPACE.'\\Length':
$name = self::BASE_NAMESPACE.'\\LegacyLengthValidator';
break;
case self::FORM_BASE_NAMESPACE.'\\Form':
$name = self::FORM_BASE_NAMESPACE.'\\LegacyFormValidator';
break;
}
$this->validators[$name] = new $name();
} elseif (is_string($this->validators[$name])) {
$this->validators[$name] = $this->container->get($this->validators[$name]);
}
if (!$this->validators[$name] instanceof ConstraintValidatorInterface) {
throw new UnexpectedTypeException($this->validators[$name], 'Symfony\Component\Validator\ConstraintValidatorInterface');
}
return $this->validators[$name];
}
}

View File

@ -15,6 +15,7 @@ use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Validator\Util\ServerParams;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
@ -53,7 +54,11 @@ class FormValidator extends ConstraintValidator
/* @var FormInterface $form */
$config = $form->getConfig();
$validator = $this->context->getValidator()->inContext($this->context);
$validator = null;
if ($this->context instanceof ExecutionContextInterface) {
$validator = $this->context->getValidator()->inContext($this->context);
}
if ($form->isSynchronized()) {
// Validate the form data only if transformation succeeded
@ -62,7 +67,12 @@ class FormValidator extends ConstraintValidator
// Validate the data against its own constraints
if (self::allowDataWalking($form)) {
foreach ($groups as $group) {
$validator->atPath('data')->validate($form->getData(), null, $group);
if ($validator) {
$validator->atPath('data')->validate($form->getData(), null, $group);
} else {
// 2.4 API
$this->context->validate($form->getData(), 'data', $group, true);
}
}
}
@ -72,7 +82,12 @@ class FormValidator extends ConstraintValidator
foreach ($constraints as $constraint) {
foreach ($groups as $group) {
if (in_array($group, $constraint->groups)) {
$validator->atPath('data')->validate($form->getData(), $constraint, $group);
if ($validator) {
$validator->atPath('data')->validate($form->getData(), $constraint, $group);
} else {
// 2.4 API
$this->context->validateValue($form->getData(), $constraint, 'data', $group);
}
// Prevent duplicate validation
continue 2;
@ -101,20 +116,40 @@ class FormValidator extends ConstraintValidator
? (string) $form->getViewData()
: gettype($form->getViewData());
$this->context->buildViolation($config->getOption('invalid_message'))
->setParameters(array_replace(array('{{ value }}' => $clientDataAsString), $config->getOption('invalid_message_parameters')))
->setInvalidValue($form->getViewData())
->setCode(Form::ERR_INVALID)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($config->getOption('invalid_message'))
->setParameters(array_replace(array('{{ value }}' => $clientDataAsString), $config->getOption('invalid_message_parameters')))
->setInvalidValue($form->getViewData())
->setCode(Form::ERR_INVALID)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation(
$config->getOption('invalid_message'),
array_replace(array('{{ value }}' => $clientDataAsString), $config->getOption('invalid_message_parameters')),
$form->getViewData(),
null,
Form::ERR_INVALID
);
}
}
}
// Mark the form with an error if it contains extra fields
if (count($form->getExtraData()) > 0) {
$this->context->buildViolation($config->getOption('extra_fields_message'))
->setParameter('{{ extra_fields }}', implode('", "', array_keys($form->getExtraData())))
->setInvalidValue($form->getExtraData())
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($config->getOption('extra_fields_message'))
->setParameter('{{ extra_fields }}', implode('", "', array_keys($form->getExtraData())))
->setInvalidValue($form->getExtraData())
->addViolation();
} else {
// 2.4 API
$this->context->addViolation(
$config->getOption('extra_fields_message'),
array('{{ extra_fields }}' => implode('", "', array_keys($form->getExtraData()))),
$form->getExtraData()
);
}
}
// Mark the form with an error if the uploaded size was too large
@ -124,10 +159,19 @@ class FormValidator extends ConstraintValidator
$max = $this->serverParams->getPostMaxSize();
if (!empty($max) && $length > $max) {
$this->context->buildViolation($config->getOption('post_max_size_message'))
->setParameter('{{ max }}', $this->serverParams->getNormalizedIniPostMaxSize())
->setInvalidValue($length)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($config->getOption('post_max_size_message'))
->setParameter('{{ max }}', $this->serverParams->getNormalizedIniPostMaxSize())
->setInvalidValue($length)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation(
$config->getOption('post_max_size_message'),
array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()),
$length
);
}
}
}
}

View File

@ -1,223 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form\Extension\Validator\Constraints;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\Extension\Validator\Util\ServerParams;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class LegacyFormValidator extends ConstraintValidator
{
/**
* @var ServerParams
*/
private $serverParams;
/**
* Creates a validator with the given server parameters.
*
* @param ServerParams $params The server parameters. Default
* parameters are created if null.
*/
public function __construct(ServerParams $params = null)
{
$this->serverParams = $params ?: new ServerParams();
}
/**
* {@inheritdoc}
*/
public function validate($form, Constraint $constraint)
{
if (!$constraint instanceof Form) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Form');
}
if (!$form instanceof FormInterface) {
return;
}
/* @var FormInterface $form */
$config = $form->getConfig();
if ($form->isSynchronized()) {
// Validate the form data only if transformation succeeded
$groups = self::getValidationGroups($form);
// Validate the data against its own constraints
if (self::allowDataWalking($form)) {
foreach ($groups as $group) {
$this->context->validate($form->getData(), 'data', $group, true);
}
}
// Validate the data against the constraints defined
// in the form
$constraints = $config->getOption('constraints');
foreach ($constraints as $constraint) {
foreach ($groups as $group) {
if (in_array($group, $constraint->groups)) {
$this->context->validateValue($form->getData(), $constraint, 'data', $group);
// Prevent duplicate validation
continue 2;
}
}
}
} else {
$childrenSynchronized = true;
foreach ($form as $child) {
if (!$child->isSynchronized()) {
$childrenSynchronized = false;
break;
}
}
// Mark the form with an error if it is not synchronized BUT all
// of its children are synchronized. If any child is not
// synchronized, an error is displayed there already and showing
// a second error in its parent form is pointless, or worse, may
// lead to duplicate errors if error bubbling is enabled on the
// child.
// See also https://github.com/symfony/symfony/issues/4359
if ($childrenSynchronized) {
$clientDataAsString = is_scalar($form->getViewData())
? (string) $form->getViewData()
: gettype($form->getViewData());
$this->context->addViolation(
$config->getOption('invalid_message'),
array_replace(array('{{ value }}' => $clientDataAsString), $config->getOption('invalid_message_parameters')),
$form->getViewData(),
null,
Form::ERR_INVALID
);
}
}
// Mark the form with an error if it contains extra fields
if (count($form->getExtraData()) > 0) {
$this->context->addViolation(
$config->getOption('extra_fields_message'),
array('{{ extra_fields }}' => implode('", "', array_keys($form->getExtraData()))),
$form->getExtraData()
);
}
// Mark the form with an error if the uploaded size was too large
$length = $this->serverParams->getContentLength();
if ($form->isRoot() && null !== $length) {
$max = $this->serverParams->getPostMaxSize();
if (!empty($max) && $length > $max) {
$this->context->addViolation(
$config->getOption('post_max_size_message'),
array('{{ max }}' => $this->serverParams->getNormalizedIniPostMaxSize()),
$length
);
}
}
}
/**
* Returns whether the data of a form may be walked.
*
* @param FormInterface $form The form to test.
*
* @return bool Whether the graph walker may walk the data.
*/
private static function allowDataWalking(FormInterface $form)
{
$data = $form->getData();
// Scalar values cannot have mapped constraints
if (!is_object($data) && !is_array($data)) {
return false;
}
// Root forms are always validated
if ($form->isRoot()) {
return true;
}
// Non-root forms are validated if validation cascading
// is enabled in all ancestor forms
while (null !== ($form = $form->getParent())) {
if (!$form->getConfig()->getOption('cascade_validation')) {
return false;
}
}
return true;
}
/**
* Returns the validation groups of the given form.
*
* @param FormInterface $form The form.
*
* @return array The validation groups.
*/
private static function getValidationGroups(FormInterface $form)
{
// Determine the clicked button of the complete form tree
$clickedButton = null;
if (method_exists($form, 'getClickedButton')) {
$clickedButton = $form->getClickedButton();
}
if (null !== $clickedButton) {
$groups = $clickedButton->getConfig()->getOption('validation_groups');
if (null !== $groups) {
return self::resolveValidationGroups($groups, $form);
}
}
do {
$groups = $form->getConfig()->getOption('validation_groups');
if (null !== $groups) {
return self::resolveValidationGroups($groups, $form);
}
$form = $form->getParent();
} while (null !== $form);
return array(Constraint::DEFAULT_GROUP);
}
/**
* Post-processes the validation groups option for a given form.
*
* @param array|callable $groups The validation groups.
* @param FormInterface $form The validated form.
*
* @return array The validation groups.
*/
private static function resolveValidationGroups($groups, FormInterface $form)
{
if (!is_string($groups) && is_callable($groups)) {
$groups = call_user_func($groups, $form);
}
return (array) $groups;
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Form\Tests\Extension\Validator\Constraints;
use Symfony\Component\Form\Extension\Validator\Constraints\LegacyFormValidator;
use Symfony\Component\Validator\Validation;
/**
@ -24,9 +23,4 @@ class LegacyFormValidator2Dot4ApiTest extends FormValidatorTest
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyFormValidator($this->serverParams);
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
@ -41,10 +42,18 @@ class AllValidator extends ConstraintValidator
$context = $this->context;
$group = $context->getGroup();
$validator = $context->getValidator()->inContext($context);
foreach ($value as $key => $element) {
$validator->atPath('['.$key.']')->validate($element, $constraint->constraints, $group);
if ($context instanceof ExecutionContextInterface) {
$validator = $context->getValidator()->inContext($context);
foreach ($value as $key => $element) {
$validator->atPath('['.$key.']')->validate($element, $constraint->constraints, $group);
}
} else {
// 2.4 API
foreach ($value as $key => $element) {
$context->validateValue($element, $constraint->constraints, '['.$key.']', $group);
}
}
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
@ -63,35 +64,63 @@ class ChoiceValidator extends ConstraintValidator
if ($constraint->multiple) {
foreach ($value as $_value) {
if (!in_array($_value, $choices, $constraint->strict)) {
$this->context->buildViolation($constraint->multipleMessage)
->setParameter('{{ value }}', $this->formatValue($_value))
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->multipleMessage)
->setParameter('{{ value }}', $this->formatValue($_value))
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->multipleMessage, array(
'{{ value }}' => $this->formatValue($_value),
));
}
}
}
$count = count($value);
if ($constraint->min !== null && $count < $constraint->min) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ limit }}', $constraint->min)
->setPlural((int) $constraint->min)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ limit }}', $constraint->min)
->setPlural((int) $constraint->min)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->minMessage, array(
'{{ limit }}' => $constraint->min
), $value, (int) $constraint->min);
}
return;
}
if ($constraint->max !== null && $count > $constraint->max) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ limit }}', $constraint->max)
->setPlural((int) $constraint->max)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ limit }}', $constraint->max)
->setPlural((int) $constraint->max)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->maxMessage, array(
'{{ limit }}' => $constraint->max
), $value, (int) $constraint->max);
}
return;
}
} elseif (!in_array($value, $choices, $constraint->strict)) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value),
));
}
}
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
@ -50,7 +51,6 @@ class CollectionValidator extends ConstraintValidator
// to validate() instead.
$context = $this->context;
$group = $context->getGroup();
$validator = $context->getValidator()->inContext($context);
foreach ($constraint->fields as $field => $fieldConstraint) {
// bug fix issue #2779
@ -59,26 +59,47 @@ class CollectionValidator extends ConstraintValidator
if ($existsInArray || $existsInArrayAccess) {
if (count($fieldConstraint->constraints) > 0) {
$validator->atPath('['.$field.']')
->validate($value[$field], $fieldConstraint->constraints, $group);
if ($context instanceof ExecutionContextInterface) {
$context->getValidator()
->inContext($context)
->atPath('['.$field.']')
->validate($value[$field], $fieldConstraint->constraints, $group);
} else {
// 2.4 API
$context->validateValue($value[$field], $fieldConstraint->constraints, '['.$field.']', $group);
}
}
} elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) {
$context->buildViolation($constraint->missingFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue(null)
->addViolation();
if ($context instanceof ExecutionContextInterface) {
$context->buildViolation($constraint->missingFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue(null)
->addViolation();
} else {
// 2.4 API
$context->addViolationAt('['.$field.']', $constraint->missingFieldsMessage, array(
'{{ field }}' => $this->formatValue($field)
), null);
}
}
}
if (!$constraint->allowExtraFields) {
foreach ($value as $field => $fieldValue) {
if (!isset($constraint->fields[$field])) {
$context->buildViolation($constraint->extraFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue($fieldValue)
->addViolation();
if ($context instanceof ExecutionContextInterface) {
$context->buildViolation($constraint->extraFieldsMessage)
->atPath('['.$field.']')
->setParameter('{{ field }}', $this->formatValue($field))
->setInvalidValue($fieldValue)
->addViolation();
} else {
// 2.4 API
$context->addViolationAt('['.$field.']', $constraint->extraFieldsMessage, array(
'{{ field }}' => $this->formatValue($field)
), $fieldValue);
}
}
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
@ -36,34 +37,58 @@ class CountValidator extends ConstraintValidator
$count = count($value);
if ($constraint->min == $constraint->max && $count != $constraint->min) {
$this->context->buildViolation($constraint->exactMessage)
->setParameter('{{ count }}', $count)
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->exactMessage)
->setParameter('{{ count }}', $count)
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->exactMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
}
return;
}
if (null !== $constraint->max && $count > $constraint->max) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ count }}', $count)
->setParameter('{{ limit }}', $constraint->max)
->setInvalidValue($value)
->setPlural((int) $constraint->max)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ count }}', $count)
->setParameter('{{ limit }}', $constraint->max)
->setInvalidValue($value)
->setPlural((int) $constraint->max)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->maxMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->max,
), $value, (int) $constraint->max);
}
return;
}
if (null !== $constraint->min && $count < $constraint->min) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ count }}', $count)
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ count }}', $count)
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->minMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
}
}
}
}

View File

@ -1,49 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.5.3, to be removed in 3.0.
*/
class LegacyAllValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof All) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\All');
}
if (null === $value) {
return;
}
if (!is_array($value) && !$value instanceof \Traversable) {
throw new UnexpectedTypeException($value, 'array or Traversable');
}
$context = $this->context;
$group = $context->getGroup();
foreach ($value as $key => $element) {
$context->validateValue($element, $constraint->constraints, '['.$key.']', $group);
}
}
}

View File

@ -1,95 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* ChoiceValidator validates that the value is one of the expected values.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Florian Eckerstorfer <florian@eckerstorfer.org>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.5.3, to be removed in 3.0.
*/
class LegacyChoiceValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Choice) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Choice');
}
if (!$constraint->choices && !$constraint->callback) {
throw new ConstraintDefinitionException('Either "choices" or "callback" must be specified on constraint Choice');
}
if (null === $value) {
return;
}
if ($constraint->multiple && !is_array($value)) {
throw new UnexpectedTypeException($value, 'array');
}
if ($constraint->callback) {
if (is_callable(array($this->context->getClassName(), $constraint->callback))) {
$choices = call_user_func(array($this->context->getClassName(), $constraint->callback));
} elseif (is_callable($constraint->callback)) {
$choices = call_user_func($constraint->callback);
} else {
throw new ConstraintDefinitionException('The Choice constraint expects a valid callback');
}
} else {
$choices = $constraint->choices;
}
if ($constraint->multiple) {
foreach ($value as $_value) {
if (!in_array($_value, $choices, $constraint->strict)) {
$this->context->addViolation($constraint->multipleMessage, array(
'{{ value }}' => $this->formatValue($_value),
));
}
}
$count = count($value);
if ($constraint->min !== null && $count < $constraint->min) {
$this->context->addViolation($constraint->minMessage, array(
'{{ limit }}' => $constraint->min
), $value, (int) $constraint->min);
return;
}
if ($constraint->max !== null && $count > $constraint->max) {
$this->context->addViolation($constraint->maxMessage, array(
'{{ limit }}' => $constraint->max
), $value, (int) $constraint->max);
return;
}
} elseif (!in_array($value, $choices, $constraint->strict)) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value),
));
}
}
}

View File

@ -1,80 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.5.3, to be removed in 3.0.
*/
class LegacyCollectionValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Collection) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Collection');
}
if (null === $value) {
return;
}
if (!is_array($value) && !($value instanceof \Traversable && $value instanceof \ArrayAccess)) {
throw new UnexpectedTypeException($value, 'array or Traversable and ArrayAccess');
}
// We need to keep the initialized context when CollectionValidator
// calls itself recursively (Collection constraints can be nested).
// Since the context of the validator is overwritten when initialize()
// is called for the nested constraint, the outer validator is
// acting on the wrong context when the nested validation terminates.
//
// A better solution - which should be approached in Symfony 3.0 - is to
// remove the initialize() method and pass the context as last argument
// to validate() instead.
$context = $this->context;
$group = $context->getGroup();
foreach ($constraint->fields as $field => $fieldConstraint) {
// bug fix issue #2779
$existsInArray = is_array($value) && array_key_exists($field, $value);
$existsInArrayAccess = $value instanceof \ArrayAccess && $value->offsetExists($field);
if ($existsInArray || $existsInArrayAccess) {
if (count($fieldConstraint->constraints) > 0) {
$context->validateValue($value[$field], $fieldConstraint->constraints, '['.$field.']', $group);
}
} elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) {
$context->addViolationAt('['.$field.']', $constraint->missingFieldsMessage, array(
'{{ field }}' => $this->formatValue($field)
), null);
}
}
if (!$constraint->allowExtraFields) {
foreach ($value as $field => $fieldValue) {
if (!isset($constraint->fields[$field])) {
$context->addViolationAt('['.$field.']', $constraint->extraFieldsMessage, array(
'{{ field }}' => $this->formatValue($field)
), $fieldValue);
}
}
}
}
}

View File

@ -1,65 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.5.3, to be removed in 3.0.
*/
class LegacyCountValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (null === $value) {
return;
}
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->context->addViolation($constraint->exactMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
return;
}
if (null !== $constraint->max && $count > $constraint->max) {
$this->context->addViolation($constraint->maxMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->max,
), $value, (int) $constraint->max);
return;
}
if (null !== $constraint->min && $count < $constraint->min) {
$this->context->addViolation($constraint->minMessage, array(
'{{ count }}' => $count,
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
}
}
}

View File

@ -1,77 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.5.3, to be removed in 3.0.
*/
class LegacyLengthValidator extends ConstraintValidator
{
/**
* {@inheritdoc}
*/
public function validate($value, Constraint $constraint)
{
if (!$constraint instanceof Length) {
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Length');
}
if (null === $value || '' === $value) {
return;
}
if (!is_scalar($value) && !(is_object($value) && method_exists($value, '__toString'))) {
throw new UnexpectedTypeException($value, 'string');
}
$stringValue = (string) $value;
if (function_exists('grapheme_strlen') && 'UTF-8' === $constraint->charset) {
$length = grapheme_strlen($stringValue);
} elseif (function_exists('mb_strlen')) {
$length = mb_strlen($stringValue, $constraint->charset);
} else {
$length = strlen($stringValue);
}
if ($constraint->min == $constraint->max && $length != $constraint->min) {
$this->context->addViolation($constraint->exactMessage, array(
'{{ value }}' => $this->formatValue($stringValue),
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
return;
}
if (null !== $constraint->max && $length > $constraint->max) {
$this->context->addViolation($constraint->maxMessage, array(
'{{ value }}' => $this->formatValue($stringValue),
'{{ limit }}' => $constraint->max,
), $value, (int) $constraint->max);
return;
}
if (null !== $constraint->min && $length < $constraint->min) {
$this->context->addViolation($constraint->minMessage, array(
'{{ value }}' => $this->formatValue($stringValue),
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
}
}
}

View File

@ -13,6 +13,7 @@ namespace Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
/**
@ -48,34 +49,58 @@ class LengthValidator extends ConstraintValidator
}
if ($constraint->min == $constraint->max && $length != $constraint->min) {
$this->context->buildViolation($constraint->exactMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->exactMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->exactMessage, array(
'{{ value }}' => $this->formatValue($stringValue),
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
}
return;
}
if (null !== $constraint->max && $length > $constraint->max) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ limit }}', $constraint->max)
->setInvalidValue($value)
->setPlural((int) $constraint->max)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->maxMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ limit }}', $constraint->max)
->setInvalidValue($value)
->setPlural((int) $constraint->max)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->maxMessage, array(
'{{ value }}' => $this->formatValue($stringValue),
'{{ limit }}' => $constraint->max,
), $value, (int) $constraint->max);
}
return;
}
if (null !== $constraint->min && $length < $constraint->min) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->minMessage)
->setParameter('{{ value }}', $this->formatValue($stringValue))
->setParameter('{{ limit }}', $constraint->min)
->setInvalidValue($value)
->setPlural((int) $constraint->min)
->addViolation();
} else {
// 2.4 API
$this->context->addViolation($constraint->minMessage, array(
'{{ value }}' => $this->formatValue($stringValue),
'{{ limit }}' => $constraint->min,
), $value, (int) $constraint->min);
}
}
}
}

View File

@ -1,71 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
/**
* Backwards compatible implementation of the {@link ConstraintValidatorFactoryInterface}.
*
* This class uses legacy constraint validators where possible to ensure
* compatibility with the 2.4 validator API.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.5.3, to be removed in 3.0.
*/
class LegacyConstraintValidatorFactory implements ConstraintValidatorFactoryInterface
{
protected $validators = array();
private $propertyAccessor;
public function __construct($propertyAccessor = null)
{
$this->propertyAccessor = $propertyAccessor;
}
/**
* {@inheritdoc}
*/
public function getInstance(Constraint $constraint)
{
switch (get_class($constraint)) {
case __NAMESPACE__.'\\Constraints\\All':
$className = __NAMESPACE__.'\\Constraints\\LegacyAllValidator';
break;
case __NAMESPACE__.'\\Constraints\\Choice':
$className = __NAMESPACE__.'\\Constraints\\LegacyChoiceValidator';
break;
case __NAMESPACE__.'\\Constraints\\Collection':
$className = __NAMESPACE__.'\\Constraints\\LegacyCollectionValidator';
break;
case __NAMESPACE__.'\\Constraints\\Count':
$className = __NAMESPACE__.'\\Constraints\\LegacyCountValidator';
break;
case __NAMESPACE__.'\\Constraints\\Length':
$className = __NAMESPACE__.'\\Constraints\\LegacyLengthValidator';
break;
default:
$className = $constraint->validatedBy();
break;
}
if (!isset($this->validators[$className])) {
$this->validators[$className] = 'validator.expression' === $className
? new ExpressionValidator($this->propertyAccessor)
: new $className();
}
return $this->validators[$className];
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyAllValidator;
use Symfony\Component\Validator\Validation;
/**
@ -24,9 +23,4 @@ class LegacyAllValidator2Dot4ApiTest extends AllValidatorTest
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyAllValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyChoiceValidator;
use Symfony\Component\Validator\Validation;
/**
@ -24,9 +23,4 @@ class LegacyChoiceValidator2Dot4ApiTest extends ChoiceValidatorTest
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyChoiceValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyCollectionValidator;
use Symfony\Component\Validator\Validation;
class LegacyCollectionValidatorArray2Dot4ApiTest extends CollectionValidatorArrayTest
@ -20,9 +19,4 @@ class LegacyCollectionValidatorArray2Dot4ApiTest extends CollectionValidatorArra
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyCollectionValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyCollectionValidator;
use Symfony\Component\Validator\Validation;
class LegacyCollectionValidatorArrayObject2Dot4ApiTest extends CollectionValidatorArrayObjectTest
@ -20,9 +19,4 @@ class LegacyCollectionValidatorArrayObject2Dot4ApiTest extends CollectionValidat
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyCollectionValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyCollectionValidator;
use Symfony\Component\Validator\Validation;
class LegacyCollectionValidatorCustomArrayObject2Dot4ApiTest extends CollectionValidatorCustomArrayObjectTest
@ -20,9 +19,4 @@ class LegacyCollectionValidatorCustomArrayObject2Dot4ApiTest extends CollectionV
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyCollectionValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyCountValidator;
use Symfony\Component\Validator\Validation;
/**
@ -24,9 +23,4 @@ class LegacyCountValidatorArray2Dot4ApiTest extends CountValidatorArrayTest
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyCountValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyCountValidator;
use Symfony\Component\Validator\Validation;
/**
@ -24,9 +23,4 @@ class LegacyCountValidatorCountable2Dot4ApiTest extends CountValidatorCountableT
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyCountValidator();
}
}

View File

@ -11,7 +11,6 @@
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\LegacyLengthValidator;
use Symfony\Component\Validator\Validation;
/**
@ -24,9 +23,4 @@ class LegacyLengthValidator2Dot4ApiTest extends LengthValidatorTest
{
return Validation::API_VERSION_2_4;
}
protected function createValidator()
{
return new LegacyLengthValidator();
}
}

View File

@ -13,10 +13,10 @@ namespace Symfony\Component\Validator\Tests;
use Symfony\Component\Validator\Constraints\Collection;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\LegacyConstraintValidatorFactory;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\ValidationVisitor;
@ -313,7 +313,7 @@ class ExecutionContextTest extends \PHPUnit_Framework_TestCase
'[name]'
);
$visitor = new ValidationVisitor('Root', $this->metadataFactory, new LegacyConstraintValidatorFactory(), $this->translator);
$visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), $this->translator);
$context = new ExecutionContext($visitor, $this->translator, self::TRANS_DOMAIN);
$context->validateValue($data, $constraints);

View File

@ -11,9 +11,9 @@
namespace Symfony\Component\Validator\Tests\Validator;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\Context\LegacyExecutionContextFactory;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\LegacyConstraintValidatorFactory;
use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Validator\LegacyValidator;
@ -31,7 +31,7 @@ class LegacyValidator2Dot5ApiTest extends Abstract2Dot5ApiTest
protected function createValidator(MetadataFactoryInterface $metadataFactory, array $objectInitializers = array())
{
$contextFactory = new LegacyExecutionContextFactory($metadataFactory, new DefaultTranslator());
$validatorFactory = new LegacyConstraintValidatorFactory();
$validatorFactory = new ConstraintValidatorFactory();
return new LegacyValidator($contextFactory, $metadataFactory, $validatorFactory, $objectInitializers);
}

View File

@ -11,9 +11,9 @@
namespace Symfony\Component\Validator\Tests\Validator;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\Context\LegacyExecutionContextFactory;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\LegacyConstraintValidatorFactory;
use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Validator\LegacyValidator;
@ -31,7 +31,7 @@ class LegacyValidatorLegacyApiTest extends AbstractLegacyApiTest
protected function createValidator(MetadataFactoryInterface $metadataFactory, array $objectInitializers = array())
{
$contextFactory = new LegacyExecutionContextFactory($metadataFactory, new DefaultTranslator());
$validatorFactory = new LegacyConstraintValidatorFactory();
$validatorFactory = new ConstraintValidatorFactory();
return new LegacyValidator($contextFactory, $metadataFactory, $validatorFactory, $objectInitializers);
}

View File

@ -380,7 +380,7 @@ class ValidatorBuilder implements ValidatorBuilderInterface
$metadataFactory = new ClassMetadataFactory($loader, $this->metadataCache);
}
$validatorFactory = $this->validatorFactory;
$validatorFactory = $this->validatorFactory ?: new ConstraintValidatorFactory($this->propertyAccessor);
$translator = $this->translator ?: new DefaultTranslator();
$apiVersion = $this->apiVersion;
@ -391,20 +391,16 @@ class ValidatorBuilder implements ValidatorBuilderInterface
}
if (Validation::API_VERSION_2_4 === $apiVersion) {
$validatorFactory = $validatorFactory ?: new ConstraintValidatorFactory($this->propertyAccessor);
return new ValidatorV24($metadataFactory, $validatorFactory, $translator, $this->translationDomain, $this->initializers);
}
if (Validation::API_VERSION_2_5 === $apiVersion) {
$contextFactory = new ExecutionContextFactory($translator, $this->translationDomain);
$validatorFactory = $validatorFactory ?: new ConstraintValidatorFactory($this->propertyAccessor);
return new RecursiveValidator($contextFactory, $metadataFactory, $validatorFactory, $this->initializers);
}
$contextFactory = new LegacyExecutionContextFactory($metadataFactory, $translator, $this->translationDomain);
$validatorFactory = $validatorFactory ?: new LegacyConstraintValidatorFactory($this->propertyAccessor);
return new LegacyValidator($contextFactory, $metadataFactory, $validatorFactory, $this->initializers);
}