Skip to content

Commit

Permalink
[Validator] Added ConstraintValidator::buildViolation() helper for BC…
Browse files Browse the repository at this point in the history
… with 2.4 API
  • Loading branch information
webmozart committed Sep 25, 2014
1 parent c48ae25 commit 6b0c24a
Show file tree
Hide file tree
Showing 53 changed files with 898 additions and 627 deletions.
Expand Up @@ -262,12 +262,19 @@ public function testValidateUniquenessAfterConsideringMultipleQueryResults()

$this->validator->validate($entity1, $constraint);

$this->assertViolation('myMessage', array(), 'property.path.name', 'Foo');
$this->buildViolation('myMessage')
->atPath('property.path.name')
->setInvalidValue('Foo')
->assertRaised();

$this->context->getViolations()->remove(0);

$this->validator->validate($entity2, $constraint);

$this->assertViolation('myMessage', array(), 'property.path.name', 'Foo');
$this->buildViolation('myMessage')
->atPath('property.path.name')
->setInvalidValue('Foo')
->assertRaised();
}

public function testValidateUniquenessUsingCustomRepositoryMethod()
Expand Down
Expand Up @@ -13,7 +13,6 @@

use Doctrine\Common\Persistence\ManagerRegistry;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\ConstraintValidator;
Expand Down Expand Up @@ -137,14 +136,9 @@ public function validate($entity, Constraint $constraint)

$errorPath = null !== $constraint->errorPath ? $constraint->errorPath : $fields[0];

if ($this->context instanceof ExecutionContextInterface) {
$this->context->buildViolation($constraint->message)
->atPath($errorPath)
->setInvalidValue($criteria[$fields[0]])
->addViolation();
} else {
// 2.4 API
$this->context->addViolationAt($errorPath, $constraint->message, array(), $criteria[$fields[0]]);
}
$this->buildViolation($constraint->message)
->atPath($errorPath)
->setInvalidValue($criteria[$fields[0]])
->addViolation();
}
}
Expand Up @@ -99,40 +99,20 @@ public function validate($form, Constraint $constraint)
? (string) $form->getViewData()
: gettype($form->getViewData());

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
);
}
$this->buildViolation($config->getOption('invalid_message'))
->setParameters(array_replace(array('{{ value }}' => $clientDataAsString), $config->getOption('invalid_message_parameters')))
->setInvalidValue($form->getViewData())
->setCode(Form::ERR_INVALID)
->addViolation();
}
}

// Mark the form with an error if it contains extra fields
if (count($form->getExtraData()) > 0) {
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()
);
}
$this->buildViolation($config->getOption('extra_fields_message'))
->setParameter('{{ extra_fields }}', implode('", "', array_keys($form->getExtraData())))
->setInvalidValue($form->getExtraData())
->addViolation();
}
}

Expand Down
Expand Up @@ -92,7 +92,8 @@ public function testPasswordIsNotValid()

$this->validator->validate('secret', $constraint);

$this->assertViolation('myMessage');
$this->buildViolation('myMessage')
->assertRaised();
}

/**
Expand Down
53 changes: 49 additions & 4 deletions src/Symfony/Component/Validator/ConstraintValidator.php
Expand Up @@ -11,6 +11,10 @@

namespace Symfony\Component\Validator;

use Symfony\Component\Validator\Context\ExecutionContextInterface as ExecutionContextInterface2Dot5;
use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface;
use Symfony\Component\Validator\Violation\LegacyConstraintViolationBuilder;

/**
* Base class for constraint validators
*
Expand All @@ -24,14 +28,14 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
* Whether to format {@link \DateTime} objects as RFC-3339 dates
* ("Y-m-d H:i:s").
*
* @var integer
* @var int
*/
const PRETTY_DATE = 1;

/**
* Whether to cast objects with a "__toString()" method to strings.
*
* @var integer
* @var int
*/
const OBJECT_TO_STRING = 2;

Expand All @@ -48,6 +52,47 @@ public function initialize(ExecutionContextInterface $context)
$this->context = $context;
}

/**
* Wrapper for {@link ExecutionContextInterface::buildViolation} that
* supports the 2.4 context API.
*
* @param string $message The violation message
* @param array $parameters The message parameters
*
* @return ConstraintViolationBuilderInterface The violation builder
*
* @deprecated This method will be removed in Symfony 3.0.
*/
protected function buildViolation($message, array $parameters = array())
{
if ($this->context instanceof ExecutionContextInterface2Dot5) {
return $this->context->buildViolation($message, $parameters);
}

return new LegacyConstraintViolationBuilder($this->context, $message, $parameters);
}

/**
* Wrapper for {@link ExecutionContextInterface::buildViolation} that
* supports the 2.4 context API.
*
* @param ExecutionContextInterface $context The context to use
* @param string $message The violation message
* @param array $parameters The message parameters
*
* @return ConstraintViolationBuilderInterface The violation builder
*
* @deprecated This method will be removed in Symfony 3.0.
*/
protected function buildViolationInContext(ExecutionContextInterface $context, $message, array $parameters = array())
{
if ($context instanceof ExecutionContextInterface2Dot5) {
return $context->buildViolation($message, $parameters);
}

return new LegacyConstraintViolationBuilder($context, $message, $parameters);
}

/**
* Returns a string representation of the type of the value.
*
Expand Down Expand Up @@ -82,7 +127,7 @@ protected function formatTypeOf($value)
* confused by the violation message.
*
* @param mixed $value The value to format as string
* @param integer $format A bitwise combination of the format
* @param int $format A bitwise combination of the format
* constants in this class
*
* @return string The string representation of the passed value
Expand Down Expand Up @@ -142,7 +187,7 @@ protected function formatValue($value, $format = 0)
* {@link formatValue()}. The values are then concatenated with commas.
*
* @param array $values A list of values
* @param integer $format A bitwise combination of the format
* @param int $format A bitwise combination of the format
* constants in this class
*
* @return string The string representation of the value list
Expand Down
Expand Up @@ -19,6 +19,7 @@
* Provides a base class for the validation of property comparisons.
*
* @author Daniel Holmes <daniel@danielholmes.org>
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractComparisonValidator extends ConstraintValidator
{
Expand All @@ -35,12 +36,14 @@ public function validate($value, Constraint $constraint)
return;
}

if (!$this->compareValues($value, $constraint->value)) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE),
'{{ compared_value }}' => $this->formatValue($constraint->value, self::OBJECT_TO_STRING | self::PRETTY_DATE),
'{{ compared_value_type }}' => $this->formatTypeOf($constraint->value),
));
$comparedValue = $constraint->value;

if (!$this->compareValues($value, $comparedValue)) {
$this->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value, self::OBJECT_TO_STRING | self::PRETTY_DATE))
->setParameter('{{ compared_value }}', $this->formatValue($comparedValue, self::OBJECT_TO_STRING | self::PRETTY_DATE))
->setParameter('{{ compared_value_type }}', $this->formatTypeOf($comparedValue))
->addViolation();
}
}

Expand Down
Expand Up @@ -32,9 +32,9 @@ public function validate($value, Constraint $constraint)
}

if ('' !== $value && null !== $value) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value),
));
$this->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();
}
}
}
2 changes: 2 additions & 0 deletions src/Symfony/Component/Validator/Constraints/CardScheme.php
Expand Up @@ -18,6 +18,8 @@
*
* @Annotation
* @Target({"PROPERTY", "METHOD", "ANNOTATION"})
*
* @author Tim Nagel <t.nagel@infinite.net.au>
*/
class CardScheme extends Constraint
{
Expand Down
Expand Up @@ -18,9 +18,11 @@
/**
* Validates that a card number belongs to a specified scheme.
*
* @author Tim Nagel <t.nagel@infinite.net.au>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @see http://en.wikipedia.org/wiki/Bank_card_number
* @see http://www.regular-expressions.info/creditcard.html
* @author Tim Nagel <t.nagel@infinite.net.au>
*/
class CardSchemeValidator extends ConstraintValidator
{
Expand Down Expand Up @@ -113,9 +115,9 @@ public function validate($value, Constraint $constraint)
}

if (!is_numeric($value)) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value),
));
$this->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();

return;
}
Expand All @@ -131,8 +133,8 @@ public function validate($value, Constraint $constraint)
}
}

$this->context->addViolation($constraint->message, array(
'{{ value }}' => $this->formatValue($value),
));
$this->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();
}
}
60 changes: 17 additions & 43 deletions src/Symfony/Component/Validator/Constraints/ChoiceValidator.php
Expand Up @@ -13,7 +13,6 @@

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;

Expand Down Expand Up @@ -64,63 +63,38 @@ public function validate($value, Constraint $constraint)
if ($constraint->multiple) {
foreach ($value as $_value) {
if (!in_array($_value, $choices, $constraint->strict)) {
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),
));
}
$this->buildViolation($constraint->multipleMessage)
->setParameter('{{ value }}', $this->formatValue($_value))
->setInvalidValue($_value)
->addViolation();

return;
}
}

$count = count($value);

if ($constraint->min !== null && $count < $constraint->min) {
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);
}
$this->buildViolation($constraint->minMessage)
->setParameter('{{ limit }}', $constraint->min)
->setPlural((int) $constraint->min)
->addViolation();

return;
}

if ($constraint->max !== null && $count > $constraint->max) {
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);
}
$this->buildViolation($constraint->maxMessage)
->setParameter('{{ limit }}', $constraint->max)
->setPlural((int) $constraint->max)
->addViolation();

return;
}
} elseif (!in_array($value, $choices, $constraint->strict)) {
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),
));
}
$this->buildViolation($constraint->message)
->setParameter('{{ value }}', $this->formatValue($value))
->addViolation();
}
}
}

0 comments on commit 6b0c24a

Please sign in to comment.