merged branch bschussek/issue2615 (PR #3228)

Commits
-------

2e4ebe4 [Validator] Renamed methods addViolationAtRelativePath() and getAbsolutePropertyPath() in ExecutionContext
9153f0e [Validator] Deprecated ConstraintValidator methods setMessage(), getMessageTemplate() and getMessageParameters()
0417282 [Validator] Fixed typos
a30a679 [Validator] Made ExecutionContext immutable and introduced new class GlobalExecutionContext
fe85bbd [Validator] Simplified ExecutionContext::addViolation(), added ExecutionContext::addViolationAt()
f77fd41 [Form] Fixed typos
1fc615c Fixed string access by curly brace to bracket
a103c28 [Validator] The Collection constraint adds "missing" and "extra" errors to the individual fields now
f904a9e [Validator] Fixed: GraphWalker does not add constraint violation if error message is empty
1dd302c [Validator] Fixed ConstraintViolationList::__toString() to not include dots in the output if the root is empty
1678a3d [Validator] Fixed: Validator::validateValue() propagates empty validation root instead of the provided value

Discussion
----------

[Validator] Improved "missing" and "extra" errors of Collection constraint

Bug fix: yes
Feature addition: no
Backwards compatibility break: no
Symfony2 tests pass: yes
Fixes the following tickets: #2615
Todo: -

![Travis Build Status](https://secure.travis-ci.org/bschussek/symfony.png?branch=issue2615)

Instead of a single violation

    Array:
        The fields "foo", "bar" are missing

various violations are now generated.

    Array[foo]:
        This field is missing
    Array[bar]:
        This field is missing

Apart from that, the PR contains various minor fixes to the Validator.

---------------------------------------------------------------------------

by bschussek at 2012-02-02T09:14:52Z

@fabpot Ready for merge.
This commit is contained in:
Fabien Potencier 2012-02-02 10:16:32 +01:00
commit 8245bf13d5
82 changed files with 2169 additions and 1125 deletions

View File

@ -286,6 +286,13 @@ To get the diff between two versions, go to https://github.com/symfony/symfony/c
* added a SizeLength validator * added a SizeLength validator
* improved the ImageValidator with min width, max width, min height, and max height constraints * improved the ImageValidator with min width, max width, min height, and max height constraints
* added support for MIME with wildcard in FileValidator * added support for MIME with wildcard in FileValidator
* changed Collection validator to add "missing" and "extra" errors to
individual fields
* changed default value for `extraFieldsMessage` and `missingFieldsMessage`
in Collection constraint
* made ExecutionContext immutable
* deprecated Constraint methods `setMessage`, `getMessageTemplate` and
`getMessageParameters`
### Yaml ### Yaml

View File

@ -195,3 +195,37 @@ UPGRADE FROM 2.0 to 2.1
$builder->add('tags', 'collection', array('prototype' => '__proto__')); $builder->add('tags', 'collection', array('prototype' => '__proto__'));
// results in the name "__proto__" in the template // results in the name "__proto__" in the template
* The methods `setMessage`, `getMessageTemplate` and `getMessageParameters`
in Constraint were deprecated
If you have implemented custom validators, you should use either of the
`addViolation*` methods of the context object instead.
Before:
public function isValid($value, Constraint $constraint)
{
// ...
if (!$valid) {
$this->setMessage($constraint->message, array(
'{{ value }}' => $value,
));
return false;
}
}
After:
public function isValid($value, Constraint $constraint)
{
// ...
if (!$valid) {
$this->context->addViolation($constraint->message, array(
'{{ value }}' => $value,
));
return false;
}
}

View File

@ -102,10 +102,7 @@ class UniqueEntityValidator extends ConstraintValidator
return true; return true;
} }
$oldPath = $this->context->getPropertyPath(); $this->context->addViolationAtSubPath($fields[0], $constraint->message, array(), $criteria[$fields[0]]);
$this->context->setPropertyPath( empty($oldPath) ? $fields[0] : $oldPath.'.'.$fields[0]);
$this->context->addViolation($constraint->message, array(), $criteria[$fields[0]]);
$this->context->setPropertyPath($oldPath);
return true; // all true, we added the violation already! return true; // all true, we added the violation already!
} }

View File

@ -40,7 +40,7 @@ class UserPasswordValidator extends ConstraintValidator
$encoder = $this->encoderFactory->getEncoder($user); $encoder = $this->encoderFactory->getEncoder($user);
if (!$encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) { if (!$encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
$this->setMessage($constraint->message); $this->context->addViolation($constraint->message);
return false; return false;
} }

View File

@ -111,10 +111,6 @@ class DelegatingValidator implements FormValidatorInterface
$propertyPath = $context->getPropertyPath(); $propertyPath = $context->getPropertyPath();
$graphWalker = $context->getGraphWalker(); $graphWalker = $context->getGraphWalker();
// The Execute constraint is called on class level, so we need to
// set the property manually
$context->setCurrentProperty('data');
// Adjust the property path accordingly // Adjust the property path accordingly
if (!empty($propertyPath)) { if (!empty($propertyPath)) {
$propertyPath .= '.'; $propertyPath .= '.';
@ -134,10 +130,6 @@ class DelegatingValidator implements FormValidatorInterface
$propertyPath = $context->getPropertyPath(); $propertyPath = $context->getPropertyPath();
$graphWalker = $context->getGraphWalker(); $graphWalker = $context->getGraphWalker();
// The Execute constraint is called on class level, so we need to
// set the property manually
$context->setCurrentProperty('children');
// Adjust the property path accordingly // Adjust the property path accordingly
if (!empty($propertyPath)) { if (!empty($propertyPath)) {
$propertyPath .= '.'; $propertyPath .= '.';

View File

@ -11,7 +11,11 @@
namespace Symfony\Component\Validator; namespace Symfony\Component\Validator;
/* /**
* Base class for constraint validators
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api * @api
*/ */
abstract class ConstraintValidator implements ConstraintValidatorInterface abstract class ConstraintValidator implements ConstraintValidatorInterface
@ -20,12 +24,18 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
* @var ExecutionContext * @var ExecutionContext
*/ */
protected $context; protected $context;
/** /**
* @var string * @var string
*
* @deprecated
*/ */
private $messageTemplate; private $messageTemplate;
/** /**
* @var array * @var array
*
* @deprecated
*/ */
private $messageParameters; private $messageParameters;
@ -42,7 +52,7 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
* @api * @deprecated
*/ */
public function getMessageTemplate() public function getMessageTemplate()
{ {
@ -52,7 +62,7 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
/** /**
* {@inheritDoc} * {@inheritDoc}
* *
* @api * @deprecated
*/ */
public function getMessageParameters() public function getMessageParameters()
{ {
@ -60,11 +70,15 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
} }
/** /**
* @api * Wrapper for $this->context->addViolation()
*
* @deprecated
*/ */
protected function setMessage($template, array $parameters = array()) protected function setMessage($template, array $parameters = array())
{ {
$this->messageTemplate = $template; $this->messageTemplate = $template;
$this->messageParameters = $parameters; $this->messageParameters = $parameters;
$this->context->addViolation($template, $parameters);
} }
} }

View File

@ -12,6 +12,8 @@
namespace Symfony\Component\Validator; namespace Symfony\Component\Validator;
/** /**
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @api * @api
*/ */
interface ConstraintValidatorInterface interface ConstraintValidatorInterface
@ -34,18 +36,4 @@ interface ConstraintValidatorInterface
* @api * @api
*/ */
function isValid($value, Constraint $constraint); function isValid($value, Constraint $constraint);
/**
* @return string
*
* @api
*/
function getMessageTemplate();
/**
* @return array
*
* @api
*/
function getMessageParameters();
} }

View File

@ -33,6 +33,21 @@ class ConstraintViolation
$this->invalidValue = $invalidValue; $this->invalidValue = $invalidValue;
} }
/**
* @return string
*/
public function __toString()
{
$class = (string) (is_object($this->root) ? get_class($this->root) : $this->root);
$propertyPath = (string) $this->propertyPath;
if ('' !== $propertyPath && '[' !== $propertyPath[0] && '' !== $class) {
$class .= '.';
}
return $class . $propertyPath . ":\n " . $this->getMessage();
}
/** /**
* @return string * @return string
* *
@ -62,7 +77,15 @@ class ConstraintViolation
*/ */
public function getMessage() public function getMessage()
{ {
return strtr($this->messageTemplate, $this->messageParameters); $parameters = $this->messageParameters;
foreach ($parameters as $i => $parameter) {
if (is_array($parameter)) {
$parameters[$i] = 'Array';
}
}
return strtr($this->messageTemplate, $parameters);
} }
public function getRoot() public function getRoot()

View File

@ -12,14 +12,33 @@
namespace Symfony\Component\Validator; namespace Symfony\Component\Validator;
/** /**
* An array-acting object that holds many ConstrainViolation instances. * A list of ConstrainViolation objects.
*
* @author Bernhard Schussek <bschussek@gmail.com>
* *
* @api * @api
*/ */
class ConstraintViolationList implements \IteratorAggregate, \Countable, \ArrayAccess class ConstraintViolationList implements \IteratorAggregate, \Countable, \ArrayAccess
{ {
/**
* The constraint violations
*
* @var array
*/
protected $violations = array(); protected $violations = array();
/**
* Creates a new constraint violation list.
*
* @param array $violations The constraint violations to add to the list
*/
public function __construct(array $violations = array())
{
foreach ($violations as $violation) {
$this->add($violation);
}
}
/** /**
* @return string * @return string
*/ */
@ -28,13 +47,7 @@ class ConstraintViolationList implements \IteratorAggregate, \Countable, \ArrayA
$string = ''; $string = '';
foreach ($this->violations as $violation) { foreach ($this->violations as $violation) {
$root = $violation->getRoot(); $string .= $violation . "\n";
$class = is_object($root) ? get_class($root) : $root;
$string .= <<<EOF
{$class}.{$violation->getPropertyPath()}:
{$violation->getMessage()}
EOF;
} }
return $string; return $string;
@ -55,13 +68,13 @@ EOF;
/** /**
* Merge an existing ConstraintViolationList into this list. * Merge an existing ConstraintViolationList into this list.
* *
* @param ConstraintViolationList $violations * @param ConstraintViolationList $otherList
* *
* @api * @api
*/ */
public function addAll(ConstraintViolationList $violations) public function addAll(ConstraintViolationList $otherList)
{ {
foreach ($violations->violations as $violation) { foreach ($otherList->violations as $violation) {
$this->violations[] = $violation; $this->violations[] = $violation;
} }
} }

View File

@ -32,7 +32,7 @@ class BlankValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if ('' !== $value && null !== $value) { if ('' !== $value && null !== $value) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -48,13 +48,7 @@ class CallbackValidator extends ConstraintValidator
} }
$methods = $constraint->methods; $methods = $constraint->methods;
$context = $this->context; $success = true;
// save context state
$currentClass = $context->getCurrentClass();
$currentProperty = $context->getCurrentProperty();
$group = $context->getGroup();
$propertyPath = $context->getPropertyPath();
foreach ($methods as $method) { foreach ($methods as $method) {
if (is_array($method) || $method instanceof \Closure) { if (is_array($method) || $method instanceof \Closure) {
@ -62,22 +56,16 @@ class CallbackValidator extends ConstraintValidator
throw new ConstraintDefinitionException(sprintf('"%s::%s" targeted by Callback constraint is not a valid callable', $method[0], $method[1])); throw new ConstraintDefinitionException(sprintf('"%s::%s" targeted by Callback constraint is not a valid callable', $method[0], $method[1]));
} }
call_user_func($method, $object, $context); $success = call_user_func($method, $object, $this->context) && $success;
} else { } else {
if (!method_exists($object, $method)) { if (!method_exists($object, $method)) {
throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist', $method)); throw new ConstraintDefinitionException(sprintf('Method "%s" targeted by Callback constraint does not exist', $method));
} }
$object->$method($context); $success = $object->$method($this->context) && $success;
} }
// restore context state
$context->setCurrentClass($currentClass);
$context->setCurrentProperty($currentProperty);
$context->setGroup($group);
$context->setPropertyPath($propertyPath);
} }
return true; return $success;
} }
} }

View File

@ -66,7 +66,7 @@ class ChoiceValidator extends ConstraintValidator
if ($constraint->multiple) { if ($constraint->multiple) {
foreach ($value as $_value) { foreach ($value as $_value) {
if (!in_array($_value, $choices, $constraint->strict)) { if (!in_array($_value, $choices, $constraint->strict)) {
$this->setMessage($constraint->multipleMessage, array('{{ value }}' => $_value)); $this->context->addViolation($constraint->multipleMessage, array('{{ value }}' => $_value));
return false; return false;
} }
@ -75,18 +75,18 @@ class ChoiceValidator extends ConstraintValidator
$count = count($value); $count = count($value);
if ($constraint->min !== null && $count < $constraint->min) { if ($constraint->min !== null && $count < $constraint->min) {
$this->setMessage($constraint->minMessage, array('{{ limit }}' => $constraint->min)); $this->context->addViolation($constraint->minMessage, array('{{ limit }}' => $constraint->min));
return false; return false;
} }
if ($constraint->max !== null && $count > $constraint->max) { if ($constraint->max !== null && $count > $constraint->max) {
$this->setMessage($constraint->maxMessage, array('{{ limit }}' => $constraint->max)); $this->context->addViolation($constraint->maxMessage, array('{{ limit }}' => $constraint->max));
return false; return false;
} }
} elseif (!in_array($value, $choices, $constraint->strict)) { } elseif (!in_array($value, $choices, $constraint->strict)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -23,8 +23,8 @@ class Collection extends Constraint
public $fields; public $fields;
public $allowExtraFields = false; public $allowExtraFields = false;
public $allowMissingFields = false; public $allowMissingFields = false;
public $extraFieldsMessage = 'The fields {{ fields }} were not expected'; public $extraFieldsMessage = 'This field was not expected';
public $missingFieldsMessage = 'The fields {{ fields }} are missing'; public $missingFieldsMessage = 'This field is missing';
/** /**
* {@inheritDoc} * {@inheritDoc}

View File

@ -46,12 +46,7 @@ class CollectionValidator extends ConstraintValidator
$group = $this->context->getGroup(); $group = $this->context->getGroup();
$propertyPath = $this->context->getPropertyPath(); $propertyPath = $this->context->getPropertyPath();
$missingFields = array(); $valid = true;
$extraFields = array();
foreach ($value as $field => $fieldValue) {
$extraFields[$field] = $fieldValue;
}
foreach ($constraint->fields as $field => $fieldConstraint) { foreach ($constraint->fields as $field => $fieldConstraint) {
if ( if (
@ -72,29 +67,25 @@ class CollectionValidator extends ConstraintValidator
foreach ($constraints as $constr) { foreach ($constraints as $constr) {
$walker->walkConstraint($constr, $value[$field], $group, $propertyPath.'['.$field.']'); $walker->walkConstraint($constr, $value[$field], $group, $propertyPath.'['.$field.']');
} }
} elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) {
unset($extraFields[$field]); $this->context->addViolationAtSubPath('['.$field.']', $constraint->missingFieldsMessage, array(
} elseif (!$fieldConstraint instanceof Optional) { '{{ field }}' => $field
$missingFields[] = $field; ), null);
$valid = false;
} }
} }
if (count($extraFields) > 0 && !$constraint->allowExtraFields) { if (!$constraint->allowExtraFields) {
$this->setMessage($constraint->extraFieldsMessage, array( foreach ($value as $field => $fieldValue) {
'{{ fields }}' => '"'.implode('", "', array_keys($extraFields)).'"' if (!isset($constraint->fields[$field])) {
)); $this->context->addViolationAtSubPath('['.$field.']', $constraint->extraFieldsMessage, array(
'{{ field }}' => $field
return false; ), $fieldValue);
$valid = false;
}
}
} }
if (count($missingFields) > 0 && !$constraint->allowMissingFields) { return $valid;
$this->setMessage($constraint->missingFieldsMessage, array(
'{{ fields }}' => '"'.implode('", "', $missingFields).'"'
));
return false;
}
return true;
} }
} }

View File

@ -47,7 +47,7 @@ class CountryValidator extends ConstraintValidator
$value = (string) $value; $value = (string) $value;
if (!in_array($value, \Symfony\Component\Locale\Locale::getCountries())) { if (!in_array($value, \Symfony\Component\Locale\Locale::getCountries())) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -48,12 +48,12 @@ class DateValidator extends ConstraintValidator
$value = (string) $value; $value = (string) $value;
if (!preg_match(static::PATTERN, $value, $matches)) { if (!preg_match(static::PATTERN, $value, $matches) || !checkdate($matches[2], $matches[3], $matches[1])) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }
return checkdate($matches[2], $matches[3], $matches[1]); return true;
} }
} }

View File

@ -58,7 +58,7 @@ class EmailValidator extends ConstraintValidator
} }
if (!$valid) { if (!$valid) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -39,7 +39,7 @@ class FalseValidator extends ConstraintValidator
return true; return true;
} }
$this->setMessage($constraint->message); $this->context->addViolation($constraint->message);
return false; return false;
} }

View File

@ -44,15 +44,15 @@ class FileValidator extends ConstraintValidator
case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_INI_SIZE:
$maxSize = UploadedFile::getMaxFilesize(); $maxSize = UploadedFile::getMaxFilesize();
$maxSize = $constraint->maxSize ? min($maxSize, $constraint->maxSize) : $maxSize; $maxSize = $constraint->maxSize ? min($maxSize, $constraint->maxSize) : $maxSize;
$this->setMessage($constraint->uploadIniSizeErrorMessage, array('{{ limit }}' => $maxSize.' bytes')); $this->context->addViolation($constraint->uploadIniSizeErrorMessage, array('{{ limit }}' => $maxSize.' bytes'));
return false; return false;
case UPLOAD_ERR_FORM_SIZE: case UPLOAD_ERR_FORM_SIZE:
$this->setMessage($constraint->uploadFormSizeErrorMessage); $this->context->addViolation($constraint->uploadFormSizeErrorMessage);
return false; return false;
default: default:
$this->setMessage($constraint->uploadErrorMessage); $this->context->addViolation($constraint->uploadErrorMessage);
return false; return false;
} }
@ -65,13 +65,13 @@ class FileValidator extends ConstraintValidator
$path = $value instanceof FileObject ? $value->getPathname() : (string) $value; $path = $value instanceof FileObject ? $value->getPathname() : (string) $value;
if (!is_file($path)) { if (!is_file($path)) {
$this->setMessage($constraint->notFoundMessage, array('{{ file }}' => $path)); $this->context->addViolation($constraint->notFoundMessage, array('{{ file }}' => $path));
return false; return false;
} }
if (!is_readable($path)) { if (!is_readable($path)) {
$this->setMessage($constraint->notReadableMessage, array('{{ file }}' => $path)); $this->context->addViolation($constraint->notReadableMessage, array('{{ file }}' => $path));
return false; return false;
} }
@ -94,7 +94,7 @@ class FileValidator extends ConstraintValidator
} }
if ($size > $limit) { if ($size > $limit) {
$this->setMessage($constraint->maxSizeMessage, array( $this->context->addViolation($constraint->maxSizeMessage, array(
'{{ size }}' => $size.$suffix, '{{ size }}' => $size.$suffix,
'{{ limit }}' => $limit.$suffix, '{{ limit }}' => $limit.$suffix,
'{{ file }}' => $path, '{{ file }}' => $path,
@ -128,7 +128,7 @@ class FileValidator extends ConstraintValidator
} }
if (false === $valid) { if (false === $valid) {
$this->setMessage($constraint->mimeTypesMessage, array( $this->context->addViolation($constraint->mimeTypesMessage, array(
'{{ type }}' => '"'.$mime.'"', '{{ type }}' => '"'.$mime.'"',
'{{ types }}' => '"'.implode('", "', $mimeTypes) .'"', '{{ types }}' => '"'.implode('", "', $mimeTypes) .'"',
'{{ file }}' => $path, '{{ file }}' => $path,

View File

@ -40,7 +40,7 @@ class ImageValidator extends FileValidator
$size = @getimagesize($value); $size = @getimagesize($value);
if (empty($size) || ($size[0] === 0) || ($size[1] === 0)) { if (empty($size) || ($size[0] === 0) || ($size[1] === 0)) {
$this->setMessage($constraint->sizeNotDetectedMessage); $this->context->addViolation($constraint->sizeNotDetectedMessage);
return false; return false;
} }
@ -54,7 +54,7 @@ class ImageValidator extends FileValidator
} }
if ($width < $constraint->minWidth) { if ($width < $constraint->minWidth) {
$this->setMessage($constraint->minWidthMessage, array( $this->context->addViolation($constraint->minWidthMessage, array(
'{{ width }}' => $width, '{{ width }}' => $width,
'{{ min_width }}' => $constraint->minWidth '{{ min_width }}' => $constraint->minWidth
)); ));
@ -69,7 +69,7 @@ class ImageValidator extends FileValidator
} }
if ($width > $constraint->maxWidth) { if ($width > $constraint->maxWidth) {
$this->setMessage($constraint->maxWidthMessage, array( $this->context->addViolation($constraint->maxWidthMessage, array(
'{{ width }}' => $width, '{{ width }}' => $width,
'{{ max_width }}' => $constraint->maxWidth '{{ max_width }}' => $constraint->maxWidth
)); ));
@ -84,7 +84,7 @@ class ImageValidator extends FileValidator
} }
if ($height < $constraint->minHeight) { if ($height < $constraint->minHeight) {
$this->setMessage($constraint->minHeightMessage, array( $this->context->addViolation($constraint->minHeightMessage, array(
'{{ height }}' => $height, '{{ height }}' => $height,
'{{ min_height }}' => $constraint->minHeight '{{ min_height }}' => $constraint->minHeight
)); ));
@ -99,7 +99,7 @@ class ImageValidator extends FileValidator
} }
if ($height > $constraint->maxHeight) { if ($height > $constraint->maxHeight) {
$this->setMessage($constraint->maxHeightMessage, array( $this->context->addViolation($constraint->maxHeightMessage, array(
'{{ height }}' => $height, '{{ height }}' => $height,
'{{ max_height }}' => $constraint->maxHeight '{{ max_height }}' => $constraint->maxHeight
)); ));

View File

@ -98,7 +98,7 @@ class IpValidator extends ConstraintValidator
} }
if (!filter_var($value, FILTER_VALIDATE_IP, $flag)) { if (!filter_var($value, FILTER_VALIDATE_IP, $flag)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -47,7 +47,7 @@ class LanguageValidator extends ConstraintValidator
$value = (string) $value; $value = (string) $value;
if (!in_array($value, \Symfony\Component\Locale\Locale::getLanguages())) { if (!in_array($value, \Symfony\Component\Locale\Locale::getLanguages())) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -47,7 +47,7 @@ class LocaleValidator extends ConstraintValidator
$value = (string) $value; $value = (string) $value;
if (!in_array($value, \Symfony\Component\Locale\Locale::getLocales())) { if (!in_array($value, \Symfony\Component\Locale\Locale::getLocales())) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -51,7 +51,7 @@ class MaxLengthValidator extends ConstraintValidator
} }
if ($length > $constraint->limit) { if ($length > $constraint->limit) {
$this->setMessage($constraint->message, array( $this->context->addViolation($constraint->message, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->limit, '{{ limit }}' => $constraint->limit,
)); ));

View File

@ -36,7 +36,7 @@ class MaxValidator extends ConstraintValidator
} }
if (!is_numeric($value)) { if (!is_numeric($value)) {
$this->setMessage($constraint->invalidMessage, array( $this->context->addViolation($constraint->invalidMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->limit, '{{ limit }}' => $constraint->limit,
)); ));
@ -45,7 +45,7 @@ class MaxValidator extends ConstraintValidator
} }
if ($value > $constraint->limit) { if ($value > $constraint->limit) {
$this->setMessage($constraint->message, array( $this->context->addViolation($constraint->message, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->limit, '{{ limit }}' => $constraint->limit,
)); ));

View File

@ -51,7 +51,7 @@ class MinLengthValidator extends ConstraintValidator
} }
if ($length < $constraint->limit) { if ($length < $constraint->limit) {
$this->setMessage($constraint->message, array( $this->context->addViolation($constraint->message, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->limit, '{{ limit }}' => $constraint->limit,
)); ));

View File

@ -36,7 +36,7 @@ class MinValidator extends ConstraintValidator
} }
if (!is_numeric($value)) { if (!is_numeric($value)) {
$this->setMessage($constraint->invalidMessage, array( $this->context->addViolation($constraint->invalidMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->limit, '{{ limit }}' => $constraint->limit,
)); ));
@ -45,7 +45,7 @@ class MinValidator extends ConstraintValidator
} }
if ($value < $constraint->limit) { if ($value < $constraint->limit) {
$this->setMessage($constraint->message, array( $this->context->addViolation($constraint->message, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->limit, '{{ limit }}' => $constraint->limit,
)); ));

View File

@ -32,7 +32,7 @@ class NotBlankValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if (false === $value || (empty($value) && '0' != $value)) { if (false === $value || (empty($value) && '0' != $value)) {
$this->setMessage($constraint->message); $this->context->addViolation($constraint->message);
return false; return false;
} }

View File

@ -32,7 +32,7 @@ class NotNullValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if (null === $value) { if (null === $value) {
$this->setMessage($constraint->message); $this->context->addViolation($constraint->message);
return false; return false;
} }

View File

@ -32,7 +32,7 @@ class NullValidator extends ConstraintValidator
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if (null !== $value) { if (null !== $value) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -48,7 +48,7 @@ class RegexValidator extends ConstraintValidator
$value = (string) $value; $value = (string) $value;
if ($constraint->match xor preg_match($constraint->pattern, $value)) { if ($constraint->match xor preg_match($constraint->pattern, $value)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -51,7 +51,7 @@ class SizeLengthValidator extends ConstraintValidator
} }
if ($constraint->min == $constraint->max && $length != $constraint->max) { if ($constraint->min == $constraint->max && $length != $constraint->max) {
$this->setMessage($constraint->exactMessage, array( $this->context->addViolation($constraint->exactMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->max, '{{ limit }}' => $constraint->max,
)); ));
@ -60,7 +60,7 @@ class SizeLengthValidator extends ConstraintValidator
} }
if ($length > $constraint->max) { if ($length > $constraint->max) {
$this->setMessage($constraint->maxMessage, array( $this->context->addViolation($constraint->maxMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->max, '{{ limit }}' => $constraint->max,
)); ));
@ -69,7 +69,7 @@ class SizeLengthValidator extends ConstraintValidator
} }
if ($length < $constraint->min) { if ($length < $constraint->min) {
$this->setMessage($constraint->minMessage, array( $this->context->addViolation($constraint->minMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->min, '{{ limit }}' => $constraint->min,
)); ));

View File

@ -36,7 +36,7 @@ class SizeValidator extends ConstraintValidator
} }
if (!is_numeric($value)) { if (!is_numeric($value)) {
$this->setMessage($constraint->invalidMessage, array( $this->context->addViolation($constraint->invalidMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
)); ));
@ -44,7 +44,7 @@ class SizeValidator extends ConstraintValidator
} }
if ($value > $constraint->max) { if ($value > $constraint->max) {
$this->setMessage($constraint->maxMessage, array( $this->context->addViolation($constraint->maxMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->max, '{{ limit }}' => $constraint->max,
)); ));
@ -53,7 +53,7 @@ class SizeValidator extends ConstraintValidator
} }
if ($value < $constraint->min) { if ($value < $constraint->min) {
$this->setMessage($constraint->minMessage, array( $this->context->addViolation($constraint->minMessage, array(
'{{ value }}' => $value, '{{ value }}' => $value,
'{{ limit }}' => $constraint->min, '{{ limit }}' => $constraint->min,
)); ));

View File

@ -49,7 +49,7 @@ class TimeValidator extends ConstraintValidator
$value = (string) $value; $value = (string) $value;
if (!preg_match(static::PATTERN, $value)) { if (!preg_match(static::PATTERN, $value)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -39,7 +39,7 @@ class TrueValidator extends ConstraintValidator
return true; return true;
} }
$this->setMessage($constraint->message); $this->context->addViolation($constraint->message);
return false; return false;
} }

View File

@ -48,8 +48,8 @@ class TypeValidator extends ConstraintValidator
return true; return true;
} }
$this->setMessage($constraint->message, array( $this->context->addViolation($constraint->message, array(
'{{ value }}' => is_object($value) ? get_class($value) : is_array($value) ? 'Array' : (string) $value, '{{ value }}' => is_object($value) ? get_class($value) : (is_array($value) ? 'Array' : (string) $value),
'{{ type }}' => $constraint->type, '{{ type }}' => $constraint->type,
)); ));

View File

@ -60,7 +60,7 @@ class UrlValidator extends ConstraintValidator
$pattern = sprintf(static::PATTERN, implode('|', $constraint->protocols)); $pattern = sprintf(static::PATTERN, implode('|', $constraint->protocols));
if (!preg_match($pattern, $value)) { if (!preg_match($pattern, $value)) {
$this->setMessage($constraint->message, array('{{ value }}' => $value)); $this->context->addViolation($constraint->message, array('{{ value }}' => $value));
return false; return false;
} }

View File

@ -14,55 +14,102 @@ namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface; use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
/** /**
* The central object representing a single validation process. * Stores the state of the current node in the validation graph.
* *
* This object is used by the GraphWalker to initialize validation of different * This class is immutable by design.
* items and keep track of the violations. *
* It is used by the GraphWalker to initialize validation of different items
* and keep track of the violations.
* *
* @author Fabien Potencier <fabien@symfony.com> * @author Fabien Potencier <fabien@symfony.com>
* @author Bernhard Schussek <bernhard.schussek@symfony.com> * @author Bernhard Schussek <bschussek@gmail.com>
* *
* @api * @api
*/ */
class ExecutionContext class ExecutionContext
{ {
protected $root; private $globalContext;
protected $propertyPath; private $propertyPath;
protected $class; private $value;
protected $property; private $group;
protected $group; private $class;
protected $violations; private $property;
protected $graphWalker;
protected $metadataFactory;
public function __construct( public function __construct(GlobalExecutionContext $globalContext, $value, $propertyPath, $group, $class = null, $property = null)
$root,
GraphWalker $graphWalker,
ClassMetadataFactoryInterface $metadataFactory
)
{ {
$this->root = $root; $this->globalContext = $globalContext;
$this->graphWalker = $graphWalker; $this->value = $value;
$this->metadataFactory = $metadataFactory; $this->propertyPath = $propertyPath;
$this->violations = new ConstraintViolationList(); $this->group = $group;
$this->class = $class;
$this->property = $property;
} }
public function __clone() public function __clone()
{ {
$this->violations = clone $this->violations; $this->globalContext = clone $this->globalContext;
} }
/** /**
* Adds a violation at the current node of the validation graph.
*
* @param string $message The error message.
* @param array $params The parameters parsed into the error message.
* @param mixed $invalidValue The invalid, validated value.
*
* @api * @api
*/ */
public function addViolation($message, array $params, $invalidValue) public function addViolation($message, array $params = array(), $invalidValue = null)
{ {
$this->violations->add(new ConstraintViolation( $this->globalContext->addViolation(new ConstraintViolation(
$message, $message,
$params, $params,
$this->root, $this->globalContext->getRoot(),
$this->propertyPath, $this->propertyPath,
$invalidValue // check using func_num_args() to allow passing null values
func_num_args() === 3 ? $invalidValue : $this->value
));
}
/**
* Adds a violation at the validation graph node with the given property
* path.
*
* @param string $propertyPath The property path for the violation.
* @param string $message The error message.
* @param array $params The parameters parsed into the error message.
* @param mixed $invalidValue The invalid, validated value.
*/
public function addViolationAtPath($propertyPath, $message, array $params = array(), $invalidValue = null)
{
$this->globalContext->addViolation(new ConstraintViolation(
$message,
$params,
$this->globalContext->getRoot(),
$propertyPath,
// check using func_num_args() to allow passing null values
func_num_args() === 4 ? $invalidValue : $this->value
));
}
/**
* Adds a violation at the validation graph node with the given property
* path relative to the current property path.
*
* @param string $subPath The relative property path for the violation.
* @param string $message The error message.
* @param array $params The parameters parsed into the error message.
* @param mixed $invalidValue The invalid, validated value.
*/
public function addViolationAtSubPath($subPath, $message, array $params = array(), $invalidValue = null)
{
$this->globalContext->addViolation(new ConstraintViolation(
$message,
$params,
$this->globalContext->getRoot(),
$this->getPropertyPath($subPath),
// check using func_num_args() to allow passing null values
func_num_args() === 4 ? $invalidValue : $this->value
)); ));
} }
@ -73,27 +120,21 @@ class ExecutionContext
*/ */
public function getViolations() public function getViolations()
{ {
return $this->violations; return $this->globalContext->getViolations();
} }
public function getRoot() public function getRoot()
{ {
return $this->root; return $this->globalContext->getRoot();
} }
public function setPropertyPath($propertyPath) public function getPropertyPath($subPath = null)
{ {
$this->propertyPath = $propertyPath; if (null !== $subPath && '' !== $this->propertyPath && '' !== $subPath && '[' !== $subPath[0]) {
} return $this->propertyPath . '.' . $subPath;
}
public function getPropertyPath() return $this->propertyPath . $subPath;
{
return $this->propertyPath;
}
public function setCurrentClass($class)
{
$this->class = $class;
} }
public function getCurrentClass() public function getCurrentClass()
@ -101,19 +142,14 @@ class ExecutionContext
return $this->class; return $this->class;
} }
public function setCurrentProperty($property)
{
$this->property = $property;
}
public function getCurrentProperty() public function getCurrentProperty()
{ {
return $this->property; return $this->property;
} }
public function setGroup($group) public function getCurrentValue()
{ {
$this->group = $group; return $this->value;
} }
public function getGroup() public function getGroup()
@ -126,7 +162,7 @@ class ExecutionContext
*/ */
public function getGraphWalker() public function getGraphWalker()
{ {
return $this->graphWalker; return $this->globalContext->getGraphWalker();
} }
/** /**
@ -134,6 +170,6 @@ class ExecutionContext
*/ */
public function getMetadataFactory() public function getMetadataFactory()
{ {
return $this->metadataFactory; return $this->globalContext->getMetadataFactory();
} }
} }

View File

@ -0,0 +1,76 @@
<?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\Mapping\ClassMetadataFactoryInterface;
/**
* Stores the node-independent information of a validation run.
*
* This class is immutable by design, except for violation tracking.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class GlobalExecutionContext
{
private $root;
private $graphWalker;
private $metadataFactory;
private $violations;
public function __construct($root, GraphWalker $graphWalker, ClassMetadataFactoryInterface $metadataFactory)
{
$this->root = $root;
$this->graphWalker = $graphWalker;
$this->metadataFactory = $metadataFactory;
$this->violations = new ConstraintViolationList();
}
public function __clone()
{
$this->violations = clone $this->violations;
}
public function addViolation(ConstraintViolation $violation)
{
$this->violations->add($violation);
}
/**
* @return ConstraintViolationList
*/
public function getViolations()
{
return $this->violations;
}
public function getRoot()
{
return $this->root;
}
/**
* @return GraphWalker
*/
public function getGraphWalker()
{
return $this->graphWalker;
}
/**
* @return ClassMetadataFactoryInterface
*/
public function getMetadataFactory()
{
return $this->metadataFactory;
}
}

View File

@ -27,15 +27,15 @@ use Symfony\Component\Validator\Mapping\MemberMetadata;
*/ */
class GraphWalker class GraphWalker
{ {
protected $context; private $globalContext;
protected $validatorFactory; private $validatorFactory;
protected $metadataFactory; private $metadataFactory;
protected $validatorInitializers = array(); private $validatorInitializers = array();
protected $validatedObjects = array(); private $validatedObjects = array();
public function __construct($root, ClassMetadataFactoryInterface $metadataFactory, ConstraintValidatorFactoryInterface $factory, array $validatorInitializers = array()) public function __construct($root, ClassMetadataFactoryInterface $metadataFactory, ConstraintValidatorFactoryInterface $factory, array $validatorInitializers = array())
{ {
$this->context = new ExecutionContext($root, $this, $metadataFactory); $this->globalContext = new GlobalExecutionContext($root, $this, $metadataFactory);
$this->validatorFactory = $factory; $this->validatorFactory = $factory;
$this->metadataFactory = $metadataFactory; $this->metadataFactory = $metadataFactory;
$this->validatorInitializers = $validatorInitializers; $this->validatorInitializers = $validatorInitializers;
@ -46,7 +46,7 @@ class GraphWalker
*/ */
public function getViolations() public function getViolations()
{ {
return $this->context->getViolations(); return $this->globalContext->getViolations();
} }
/** /**
@ -67,8 +67,6 @@ class GraphWalker
$initializer->initialize($object); $initializer->initialize($object);
} }
$this->context->setCurrentClass($metadata->getClassName());
if ($group === Constraint::DEFAULT_GROUP && $metadata->hasGroupSequence()) { if ($group === Constraint::DEFAULT_GROUP && $metadata->hasGroupSequence()) {
$groups = $metadata->getGroupSequence(); $groups = $metadata->getGroupSequence();
foreach ($groups as $group) { foreach ($groups as $group) {
@ -100,8 +98,10 @@ class GraphWalker
// traversing the object graph // traversing the object graph
$this->validatedObjects[$hash][$group] = true; $this->validatedObjects[$hash][$group] = true;
$currentClass = $metadata->getClassName();
foreach ($metadata->findConstraints($group) as $constraint) { foreach ($metadata->findConstraints($group) as $constraint) {
$this->walkConstraint($constraint, $object, $group, $propertyPath); $this->walkConstraint($constraint, $object, $group, $propertyPath, $currentClass);
} }
if (null !== $object) { if (null !== $object) {
@ -129,11 +129,11 @@ class GraphWalker
protected function walkMember(MemberMetadata $metadata, $value, $group, $propertyPath, $propagatedGroup = null) protected function walkMember(MemberMetadata $metadata, $value, $group, $propertyPath, $propagatedGroup = null)
{ {
$this->context->setCurrentClass($metadata->getClassName()); $currentClass = $metadata->getClassName();
$this->context->setCurrentProperty($metadata->getPropertyName()); $currentProperty = $metadata->getPropertyName();
foreach ($metadata->findConstraints($group) as $constraint) { foreach ($metadata->findConstraints($group) as $constraint) {
$this->walkConstraint($constraint, $value, $group, $propertyPath); $this->walkConstraint($constraint, $value, $group, $propertyPath, $currentClass, $currentProperty);
} }
if ($metadata->isCascaded()) { if ($metadata->isCascaded()) {
@ -164,26 +164,20 @@ class GraphWalker
} }
} }
public function walkConstraint(Constraint $constraint, $value, $group, $propertyPath) public function walkConstraint(Constraint $constraint, $value, $group, $propertyPath, $currentClass = null, $currentProperty = null)
{ {
$validator = $this->validatorFactory->getInstance($constraint); $validator = $this->validatorFactory->getInstance($constraint);
$this->context->setPropertyPath($propertyPath); $localContext = new ExecutionContext(
$this->context->setGroup($group); $this->globalContext,
$value,
$propertyPath,
$group,
$currentClass,
$currentProperty
);
$validator->initialize($this->context); $validator->initialize($localContext);
$validator->isValid($value, $constraint);
if (!$validator->isValid($value, $constraint)) {
// Resetting the property path. This is needed because some
// validators, like CollectionValidator, use the walker internally
// and so change the context.
$this->context->setPropertyPath($propertyPath);
$this->context->addViolation(
$validator->getMessageTemplate(),
$validator->getMessageParameters(),
$value
);
}
} }
} }

View File

@ -108,7 +108,7 @@ class Validator implements ValidatorInterface
return $walker->walkConstraint($constraint, $value, $group, ''); return $walker->walkConstraint($constraint, $value, $group, '');
}; };
return $this->validateGraph($value, $walk, $groups); return $this->validateGraph('', $walk, $groups);
} }
protected function validateGraph($root, \Closure $walk, $groups = null) protected function validateGraph($root, \Closure $walk, $groups = null)

View File

@ -11,6 +11,8 @@
namespace Symfony\Tests\Component\Form\Extension\Validator\Validator; namespace Symfony\Tests\Component\Form\Extension\Validator\Validator;
use Symfony\Component\Validator\GlobalExecutionContext;
use Symfony\Component\Form\FormInterface; use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\FormError; use Symfony\Component\Form\FormError;
@ -63,6 +65,15 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
return $this->getMock('Symfony\Component\Form\DataTransformerInterface', array(), array(), '', false, false); return $this->getMock('Symfony\Component\Form\DataTransformerInterface', array(), array(), '', false, false);
} }
protected function getExecutionContext($propertyPath = null)
{
$graphWalker = $this->getMockGraphWalker();
$metadataFactory = $this->getMockMetadataFactory();
$globalContext = new GlobalExecutionContext('Root', $graphWalker, $metadataFactory);
return new ExecutionContext($globalContext, null, $propertyPath, null, null, null);
}
protected function getConstraintViolation($propertyPath) protected function getConstraintViolation($propertyPath)
{ {
return new ConstraintViolation($this->message, $this->params, null, $propertyPath, null); return new ConstraintViolation($this->message, $this->params, null, $propertyPath, null);
@ -589,9 +600,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormData() public function testValidateFormData()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext();
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$form = $this->getBuilder() $form = $this->getBuilder()
->setAttribute('validation_groups', array('group1', 'group2')) ->setAttribute('validation_groups', array('group1', 'group2'))
@ -611,9 +621,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormDataCanHandleCallbackValidationGroups() public function testValidateFormDataCanHandleCallbackValidationGroups()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext();
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$form = $this->getBuilder() $form = $this->getBuilder()
->setAttribute('validation_groups', array($this, 'getValidationGroups')) ->setAttribute('validation_groups', array($this, 'getValidationGroups'))
@ -633,9 +642,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormDataCanHandleClosureValidationGroups() public function testValidateFormDataCanHandleClosureValidationGroups()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext();
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$form = $this->getBuilder() $form = $this->getBuilder()
->setAttribute('validation_groups', function(FormInterface $form){ ->setAttribute('validation_groups', function(FormInterface $form){
@ -657,10 +665,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormDataUsesInheritedValidationGroup() public function testValidateFormDataUsesInheritedValidationGroup()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext('foo.bar');
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$context->setPropertyPath('path');
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$parent = $this->getBuilder() $parent = $this->getBuilder()
@ -675,17 +681,15 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
$graphWalker->expects($this->once()) $graphWalker->expects($this->once())
->method('walkReference') ->method('walkReference')
->with($object, 'group', 'path.data', true); ->with($object, 'group', 'foo.bar.data', true);
DelegatingValidator::validateFormData($child, $context); DelegatingValidator::validateFormData($child, $context);
} }
public function testValidateFormDataUsesInheritedCallbackValidationGroup() public function testValidateFormDataUsesInheritedCallbackValidationGroup()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext('foo.bar');
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$context->setPropertyPath('path');
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$parent = $this->getBuilder() $parent = $this->getBuilder()
@ -700,20 +704,18 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
$graphWalker->expects($this->at(0)) $graphWalker->expects($this->at(0))
->method('walkReference') ->method('walkReference')
->with($object, 'group1', 'path.data', true); ->with($object, 'group1', 'foo.bar.data', true);
$graphWalker->expects($this->at(1)) $graphWalker->expects($this->at(1))
->method('walkReference') ->method('walkReference')
->with($object, 'group2', 'path.data', true); ->with($object, 'group2', 'foo.bar.data', true);
DelegatingValidator::validateFormData($child, $context); DelegatingValidator::validateFormData($child, $context);
} }
public function testValidateFormDataUsesInheritedClosureValidationGroup() public function testValidateFormDataUsesInheritedClosureValidationGroup()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext('foo.bar');
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$context->setPropertyPath('path');
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$parent = $this->getBuilder() $parent = $this->getBuilder()
@ -730,46 +732,24 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
$graphWalker->expects($this->at(0)) $graphWalker->expects($this->at(0))
->method('walkReference') ->method('walkReference')
->with($object, 'group1', 'path.data', true); ->with($object, 'group1', 'foo.bar.data', true);
$graphWalker->expects($this->at(1)) $graphWalker->expects($this->at(1))
->method('walkReference') ->method('walkReference')
->with($object, 'group2', 'path.data', true); ->with($object, 'group2', 'foo.bar.data', true);
DelegatingValidator::validateFormData($child, $context); DelegatingValidator::validateFormData($child, $context);
} }
public function testValidateFormDataAppendsPropertyPath() public function testValidateFormDataAppendsPropertyPath()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext('foo.bar');
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$context->setPropertyPath('path');
$object = $this->getMock('\stdClass'); $object = $this->getMock('\stdClass');
$form = $this->getForm(); $form = $this->getForm();
$graphWalker->expects($this->once()) $graphWalker->expects($this->once())
->method('walkReference') ->method('walkReference')
->with($object, 'Default', 'path.data', true); ->with($object, 'Default', 'foo.bar.data', true);
$form->setData($object);
DelegatingValidator::validateFormData($form, $context);
}
public function testValidateFormDataSetsCurrentPropertyToData()
{
$graphWalker = $this->getMockGraphWalker();
$metadataFactory = $this->getMockMetadataFactory();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$object = $this->getMock('\stdClass');
$form = $this->getForm();
$test = $this;
$graphWalker->expects($this->once())
->method('walkReference')
->will($this->returnCallback(function () use ($context, $test) {
$test->assertEquals('data', $context->getCurrentProperty());
}));
$form->setData($object); $form->setData($object);
@ -778,9 +758,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormDataDoesNotWalkScalars() public function testValidateFormDataDoesNotWalkScalars()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext();
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$clientTransformer = $this->getMockTransformer(); $clientTransformer = $this->getMockTransformer();
$form = $this->getBuilder() $form = $this->getBuilder()
@ -801,9 +780,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormChildren() public function testValidateFormChildren()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext();
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$form = $this->getBuilder() $form = $this->getBuilder()
->setAttribute('cascade_validation', true) ->setAttribute('cascade_validation', true)
->setAttribute('validation_groups', array('group1', 'group2')) ->setAttribute('validation_groups', array('group1', 'group2'))
@ -821,10 +799,8 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateFormChildrenAppendsPropertyPath() public function testValidateFormChildrenAppendsPropertyPath()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext('foo.bar');
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$context->setPropertyPath('path');
$form = $this->getBuilder() $form = $this->getBuilder()
->setAttribute('cascade_validation', true) ->setAttribute('cascade_validation', true)
->getForm(); ->getForm();
@ -832,36 +808,15 @@ class DelegatingValidatorTest extends \PHPUnit_Framework_TestCase
$graphWalker->expects($this->once()) $graphWalker->expects($this->once())
->method('walkReference') ->method('walkReference')
->with($form->getChildren(), 'Default', 'path.children', true); ->with($form->getChildren(), 'Default', 'foo.bar.children', true);
DelegatingValidator::validateFormChildren($form, $context);
}
public function testValidateFormChildrenSetsCurrentPropertyToData()
{
$graphWalker = $this->getMockGraphWalker();
$metadataFactory = $this->getMockMetadataFactory();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$form = $this->getBuilder()
->setAttribute('cascade_validation', true)
->getForm();
$form->add($this->getForm('firstName'));
$test = $this;
$graphWalker->expects($this->once())
->method('walkReference')
->will($this->returnCallback(function () use ($context, $test) {
$test->assertEquals('children', $context->getCurrentProperty());
}));
DelegatingValidator::validateFormChildren($form, $context); DelegatingValidator::validateFormChildren($form, $context);
} }
public function testValidateFormChildrenDoesNothingIfDisabled() public function testValidateFormChildrenDoesNothingIfDisabled()
{ {
$graphWalker = $this->getMockGraphWalker(); $context = $this->getExecutionContext();
$metadataFactory = $this->getMockMetadataFactory(); $graphWalker = $context->getGraphWalker();
$context = new ExecutionContext('Root', $graphWalker, $metadataFactory);
$form = $this->getBuilder() $form = $this->getBuilder()
->setAttribute('cascade_validation', false) ->setAttribute('cascade_validation', false)
->getForm(); ->getForm();

View File

@ -0,0 +1,134 @@
<?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\Tests\Component\Validator;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
class ConstraintViolationListTest extends \PHPUnit_Framework_TestCase
{
protected $list;
protected function setUp()
{
$this->list = new ConstraintViolationList();
}
protected function tearDown()
{
$this->list = null;
}
public function testInit()
{
$this->assertCount(0, $this->list);
}
public function testInitWithViolations()
{
$violation = $this->getViolation('Error');
$this->list = new ConstraintViolationList(array($violation));
$this->assertCount(1, $this->list);
$this->assertSame($violation, $this->list[0]);
}
public function testAdd()
{
$violation = $this->getViolation('Error');
$this->list->add($violation);
$this->assertCount(1, $this->list);
$this->assertSame($violation, $this->list[0]);
}
public function testAddAll()
{
$violations = array(
10 => $this->getViolation('Error 1'),
20 => $this->getViolation('Error 2'),
30 => $this->getViolation('Error 3'),
);
$otherList = new ConstraintViolationList($violations);
$this->list->addAll($otherList);
$this->assertCount(3, $this->list);
$this->assertSame($violations[10], $this->list[0]);
$this->assertSame($violations[20], $this->list[1]);
$this->assertSame($violations[30], $this->list[2]);
}
public function testIterator()
{
$violations = array(
10 => $this->getViolation('Error 1'),
20 => $this->getViolation('Error 2'),
30 => $this->getViolation('Error 3'),
);
$this->list = new ConstraintViolationList($violations);
// indices are reset upon adding -> array_values()
$this->assertSame(array_values($violations), iterator_to_array($this->list));
}
public function testArrayAccess()
{
$violation = $this->getViolation('Error');
$this->list[] = $violation;
$this->assertSame($violation, $this->list[0]);
$this->assertTrue(isset($this->list[0]));
unset($this->list[0]);
$this->assertFalse(isset($this->list[0]));
$this->list[10] = $violation;
$this->assertSame($violation, $this->list[10]);
$this->assertTrue(isset($this->list[10]));
}
public function testToString()
{
$this->list = new ConstraintViolationList(array(
$this->getViolation('Error 1', 'Root'),
$this->getViolation('Error 2', 'Root', 'foo.bar'),
$this->getViolation('Error 3', 'Root', '[baz]'),
$this->getViolation('Error 4', '', 'foo.bar'),
$this->getViolation('Error 5', '', '[baz]'),
));
$expected = <<<EOF
Root:
Error 1
Root.foo.bar:
Error 2
Root[baz]:
Error 3
foo.bar:
Error 4
[baz]:
Error 5
EOF;
$this->assertEquals($expected, (string) $this->list);
}
protected function getViolation($message, $root = null, $propertyPath = null)
{
return new ConstraintViolation($message, array(), $root, $propertyPath, null);
}
}

View File

@ -0,0 +1,35 @@
<?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\Tests\Component\Validator;
use Symfony\Component\Validator\ConstraintViolation;
class ConstraintViolationTest extends \PHPUnit_Framework_TestCase
{
public function testToStringHandlesArrays()
{
$violation = new ConstraintViolation(
'{{ value }}',
array('{{ value }}' => array(1, 2, 3)),
'Root',
'property.path',
null
);
$expected = <<<EOF
Root.property.path:
Array
EOF;
$this->assertSame($expected, (string) $violation);
}
}

View File

@ -11,26 +11,36 @@
namespace Symfony\Tests\Component\Validator\Constraints; namespace Symfony\Tests\Component\Validator\Constraints;
use Symfony\Component\Validator\GlobalExecutionContext;
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints\Min; use Symfony\Component\Validator\Constraints\Min;
use Symfony\Component\Validator\Constraints\Max;
use Symfony\Component\Validator\Constraints\All; use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\Constraints\AllValidator; use Symfony\Component\Validator\Constraints\AllValidator;
class AllValidatorTest extends \PHPUnit_Framework_TestCase class AllValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $validator;
protected $walker; protected $walker;
protected $context; protected $context;
protected $validator;
protected function setUp() protected function setUp()
{ {
$this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false); $this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false);
$metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface'); $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->context = new ExecutionContext('Root', $this->walker, $metadataFactory);
$this->validator = new AllValidator(); $this->validator = new AllValidator();
$this->validator->initialize($this->context); $this->validator->initialize($this->context);
$this->context->expects($this->any())
->method('getGraphWalker')
->will($this->returnValue($this->walker));
$this->context->expects($this->any())
->method('getGroup')
->will($this->returnValue('MyGroup'));
$this->context->expects($this->any())
->method('getPropertyPath')
->will($this->returnValue('foo.bar'));
} }
protected function tearDown() protected function tearDown()
@ -45,11 +55,13 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($this->validator->isValid(null, new All(new Min(4)))); $this->assertTrue($this->validator->isValid(null, new All(new Min(4))));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testThrowsExceptionIfNotTraversable() public function testThrowsExceptionIfNotTraversable()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException'); $this->validator->isValid('foo.barbar', new All(new Min(4)));
$this->validator->isValid('foobar', new All(new Min(4)));
} }
/** /**
@ -57,17 +69,19 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testWalkSingleConstraint($array) public function testWalkSingleConstraint($array)
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('foo');
$constraint = new Min(4); $constraint = new Min(4);
$i = 0;
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$this->walker->expects($this->once()) $this->walker->expects($this->at($i++))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->with($constraint, $value, 'MyGroup', 'foo.bar['.$key.']');
} }
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($array, new All($constraint))); $this->assertTrue($this->validator->isValid($array, new All($constraint)));
} }
@ -76,30 +90,32 @@ class AllValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testWalkMultipleConstraints($array) public function testWalkMultipleConstraints($array)
{ {
$this->context->setGroup('MyGroup'); $constraint1 = new Min(4);
$this->context->setPropertyPath('foo'); $constraint2 = new Max(6);
$constraint = new Min(4); $constraints = array($constraint1, $constraint2);
// can only test for twice the same constraint because PHPUnits mocking $i = 0;
// can't test method calls with different arguments
$constraints = array($constraint, $constraint);
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$this->walker->expects($this->exactly(2)) $this->walker->expects($this->at($i++))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->with($constraint1, $value, 'MyGroup', 'foo.bar['.$key.']');
$this->walker->expects($this->at($i++))
->method('walkConstraint')
->with($constraint2, $value, 'MyGroup', 'foo.bar['.$key.']');
} }
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($array, new All($constraints))); $this->assertTrue($this->validator->isValid($array, new All($constraints)));
} }
public function getValidArguments() public function getValidArguments()
{ {
return array( return array(
// can only test for one entry, because PHPUnits mocking does not allow array(array(5, 6, 7)),
// to expect multiple method calls with different arguments array(new \ArrayObject(array(5, 6, 7))),
array(array(1)),
array(new \ArrayObject(array(1))),
); );
} }
} }

View File

@ -16,34 +16,54 @@ use Symfony\Component\Validator\Constraints\BlankValidator;
class BlankValidatorTest extends \PHPUnit_Framework_TestCase class BlankValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new BlankValidator(); $this->validator = new BlankValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Blank())); $this->assertTrue($this->validator->isValid(null, new Blank()));
} }
public function testBlankIsValid() public function testBlankIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Blank())); $this->assertTrue($this->validator->isValid('', new Blank()));
} }
/** /**
* @dataProvider getInvalidValues * @dataProvider getInvalidValues
*/ */
public function testInvalidValues($date) public function testInvalidValues($value)
{ {
$this->assertFalse($this->validator->isValid($date, new Blank())); $constraint = new Blank(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
));
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
public function getInvalidValues() public function getInvalidValues()
@ -55,17 +75,4 @@ class BlankValidatorTest extends \PHPUnit_Framework_TestCase
array(1234), array(1234),
); );
} }
public function testMessageIsSet()
{
$constraint = new Blank(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -11,6 +11,7 @@
namespace Symfony\Tests\Component\Validator\Constraints; namespace Symfony\Tests\Component\Validator\Constraints;
use Symfony\Component\Validator\GlobalExecutionContext;
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\ConstraintViolation; use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList; use Symfony\Component\Validator\ConstraintViolationList;
@ -21,12 +22,9 @@ class CallbackValidatorTest_Class
{ {
public static function validateStatic($object, ExecutionContext $context) public static function validateStatic($object, ExecutionContext $context)
{ {
$context->setCurrentClass('Foo'); $context->addViolation('Static message', array('{{ value }}' => 'foobar'), 'invalidValue');
$context->setCurrentProperty('bar');
$context->setGroup('mygroup');
$context->setPropertyPath('foo.bar');
$context->addViolation('Static message', array('parameter'), 'invalidValue'); return false;
} }
} }
@ -34,126 +32,93 @@ class CallbackValidatorTest_Object
{ {
public function validateOne(ExecutionContext $context) public function validateOne(ExecutionContext $context)
{ {
$context->setCurrentClass('Foo'); $context->addViolation('My message', array('{{ value }}' => 'foobar'), 'invalidValue');
$context->setCurrentProperty('bar');
$context->setGroup('mygroup');
$context->setPropertyPath('foo.bar');
$context->addViolation('My message', array('parameter'), 'invalidValue'); return false;
} }
public function validateTwo(ExecutionContext $context) public function validateTwo(ExecutionContext $context)
{ {
$context->addViolation('Other message', array('other parameter'), 'otherInvalidValue'); $context->addViolation('Other message', array('{{ value }}' => 'baz'), 'otherInvalidValue');
return false;
} }
} }
class CallbackValidatorTest extends \PHPUnit_Framework_TestCase class CallbackValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $validator;
protected $walker;
protected $context; protected $context;
protected $validator;
protected function setUp() protected function setUp()
{ {
$this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false); $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$this->context = new ExecutionContext('Root', $this->walker, $metadataFactory);
$this->context->setCurrentClass('InitialClass');
$this->context->setCurrentProperty('initialProperty');
$this->context->setGroup('InitialGroup');
$this->context->setPropertyPath('initial.property.path');
$this->validator = new CallbackValidator(); $this->validator = new CallbackValidator();
$this->validator->initialize($this->context); $this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->validator = null;
$this->walker = null;
$this->context = null; $this->context = null;
$this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Callback(array('foo')))); $this->assertTrue($this->validator->isValid(null, new Callback(array('foo'))));
} }
public function testCallbackSingleMethod() public function testCallbackSingleMethod()
{ {
$object = new CallbackValidatorTest_Object(); $object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('validateOne'));
$this->assertTrue($this->validator->isValid($object, new Callback(array('validateOne')))); $this->context->expects($this->once())
->method('addViolation')
->with('My message', array(
'{{ value }}' => 'foobar',
));
$violations = new ConstraintViolationList(); $this->assertFalse($this->validator->isValid($object, $constraint));
$violations->add(new ConstraintViolation(
'My message',
array('parameter'),
'Root',
'foo.bar',
'invalidValue'
));
$this->assertEquals($violations, $this->context->getViolations());
$this->assertEquals('InitialClass', $this->context->getCurrentClass());
$this->assertEquals('initialProperty', $this->context->getCurrentProperty());
$this->assertEquals('InitialGroup', $this->context->getGroup());
$this->assertEquals('initial.property.path', $this->context->getPropertyPath());
} }
public function testCallbackSingleStaticMethod() public function testCallbackSingleStaticMethod()
{ {
$object = new CallbackValidatorTest_Object(); $object = new CallbackValidatorTest_Object();
$this->assertTrue($this->validator->isValid($object, new Callback(array( $this->context->expects($this->once())
array(__NAMESPACE__.'\CallbackValidatorTest_Class', 'validateStatic') ->method('addViolation')
->with('Static message', array(
'{{ value }}' => 'foobar',
));
$this->assertFalse($this->validator->isValid($object, new Callback(array(
array(__CLASS__.'_Class', 'validateStatic')
)))); ))));
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Static message',
array('parameter'),
'Root',
'foo.bar',
'invalidValue'
));
$this->assertEquals($violations, $this->context->getViolations());
$this->assertEquals('InitialClass', $this->context->getCurrentClass());
$this->assertEquals('initialProperty', $this->context->getCurrentProperty());
$this->assertEquals('InitialGroup', $this->context->getGroup());
$this->assertEquals('initial.property.path', $this->context->getPropertyPath());
} }
public function testCallbackMultipleMethods() public function testCallbackMultipleMethods()
{ {
$object = new CallbackValidatorTest_Object(); $object = new CallbackValidatorTest_Object();
$this->assertTrue($this->validator->isValid($object, new Callback(array( $this->context->expects($this->at(0))
->method('addViolation')
->with('My message', array(
'{{ value }}' => 'foobar',
));
$this->context->expects($this->at(1))
->method('addViolation')
->with('Other message', array(
'{{ value }}' => 'baz',
));
$this->assertFalse($this->validator->isValid($object, new Callback(array(
'validateOne', 'validateTwo' 'validateOne', 'validateTwo'
)))); ))));
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'My message',
array('parameter'),
'Root',
'foo.bar',
'invalidValue'
));
// context was reset
$violations->add(new ConstraintViolation(
'Other message',
array('other parameter'),
'Root',
'initial.property.path',
'otherInvalidValue'
));
$this->assertEquals($violations, $this->context->getViolations());
} }
/** /**

View File

@ -11,6 +11,8 @@
namespace Symfony\Tests\Component\Validator\Constraints; namespace Symfony\Tests\Component\Validator\Constraints;
use Symfony\Component\Validator\GlobalExecutionContext;
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints\Choice; use Symfony\Component\Validator\Constraints\Choice;
use Symfony\Component\Validator\Constraints\ChoiceValidator; use Symfony\Component\Validator\Constraints\ChoiceValidator;
@ -22,6 +24,7 @@ function choice_callback()
class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
public static function staticCallback() public static function staticCallback()
@ -31,19 +34,24 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
protected function setUp() protected function setUp()
{ {
$walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false); $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$factory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$context = new ExecutionContext('root', $walker, $factory);
$context->setCurrentClass(__CLASS__);
$this->validator = new ChoiceValidator(); $this->validator = new ChoiceValidator();
$this->validator->initialize($context); $this->validator->initialize($this->context);
$this->context->expects($this->any())
->method('getCurrentClass')
->will($this->returnValue(__CLASS__));
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectArrayIfMultipleIsTrue() public function testExpectArrayIfMultipleIsTrue()
{ {
$constraint = new Choice(array( $constraint = new Choice(array(
@ -51,27 +59,30 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'multiple' => true, 'multiple' => true,
)); ));
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid('asdf', $constraint); $this->validator->isValid('asdf', $constraint);
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Choice(array('choices' => array('foo', 'bar'))))); $this->assertTrue($this->validator->isValid(null, new Choice(array('choices' => array('foo', 'bar')))));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testChoicesOrCallbackExpected() public function testChoicesOrCallbackExpected()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
$this->validator->isValid('foobar', new Choice()); $this->validator->isValid('foobar', new Choice());
} }
/**
* @expectedException Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testValidCallbackExpected() public function testValidCallbackExpected()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
$this->validator->isValid('foobar', new Choice(array('callback' => 'abcd'))); $this->validator->isValid('foobar', new Choice(array('callback' => 'abcd')));
} }
@ -79,6 +90,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$constraint = new Choice(array('choices' => array('foo', 'bar'))); $constraint = new Choice(array('choices' => array('foo', 'bar')));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('bar', $constraint)); $this->assertTrue($this->validator->isValid('bar', $constraint));
} }
@ -86,6 +100,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback')); $constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback'));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('bar', $constraint)); $this->assertTrue($this->validator->isValid('bar', $constraint));
} }
@ -95,6 +112,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
return array('foo', 'bar'); return array('foo', 'bar');
})); }));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('bar', $constraint)); $this->assertTrue($this->validator->isValid('bar', $constraint));
} }
@ -102,6 +122,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback'))); $constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback')));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('bar', $constraint)); $this->assertTrue($this->validator->isValid('bar', $constraint));
} }
@ -109,6 +132,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$constraint = new Choice(array('callback' => 'staticCallback')); $constraint = new Choice(array('callback' => 'staticCallback'));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('bar', $constraint)); $this->assertTrue($this->validator->isValid('bar', $constraint));
} }
@ -119,6 +145,9 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'multiple' => true, 'multiple' => true,
)); ));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(array('baz', 'bar'), $constraint)); $this->assertTrue($this->validator->isValid(array('baz', 'bar'), $constraint));
} }
@ -129,11 +158,13 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'message' => 'myMessage', 'message' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => 'baz',
));
$this->assertFalse($this->validator->isValid('baz', $constraint)); $this->assertFalse($this->validator->isValid('baz', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'baz',
));
} }
public function testInvalidChoiceMultiple() public function testInvalidChoiceMultiple()
@ -144,11 +175,13 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'multiple' => true, 'multiple' => true,
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => 'baz',
));
$this->assertFalse($this->validator->isValid(array('foo', 'baz'), $constraint)); $this->assertFalse($this->validator->isValid(array('foo', 'baz'), $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'baz',
));
} }
public function testTooFewChoices() public function testTooFewChoices()
@ -160,11 +193,13 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'minMessage' => 'myMessage', 'minMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ limit }}' => 2,
));
$this->assertFalse($this->validator->isValid(array('foo'), $constraint)); $this->assertFalse($this->validator->isValid(array('foo'), $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ limit }}' => 2,
));
} }
public function testTooManyChoices() public function testTooManyChoices()
@ -176,36 +211,60 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'maxMessage' => 'myMessage', 'maxMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ limit }}' => 2,
));
$this->assertFalse($this->validator->isValid(array('foo', 'bar', 'moo'), $constraint)); $this->assertFalse($this->validator->isValid(array('foo', 'bar', 'moo'), $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ limit }}' => 2,
));
} }
public function testStrictIsFalse() public function testNonStrict()
{ {
$constraint = new Choice(array( $constraint = new Choice(array(
'choices' => array(1, 2), 'choices' => array(1, 2),
'strict' => false, 'strict' => false,
)); ));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('2', $constraint)); $this->assertTrue($this->validator->isValid('2', $constraint));
$this->assertTrue($this->validator->isValid(2, $constraint)); $this->assertTrue($this->validator->isValid(2, $constraint));
} }
public function testStrictIsTrue() public function testStrictAllowsExactValue()
{ {
$constraint = new Choice(array( $constraint = new Choice(array(
'choices' => array(1, 2), 'choices' => array(1, 2),
'strict' => true, 'strict' => true,
)); ));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(2, $constraint)); $this->assertTrue($this->validator->isValid(2, $constraint));
}
public function testStrictDisallowsDifferentType()
{
$constraint = new Choice(array(
'choices' => array(1, 2),
'strict' => true,
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => '2',
));
$this->assertFalse($this->validator->isValid('2', $constraint)); $this->assertFalse($this->validator->isValid('2', $constraint));
} }
public function testStrictIsFalseWhenMultipleChoices() public function testNonStrictWithMultipleChoices()
{ {
$constraint = new Choice(array( $constraint = new Choice(array(
'choices' => array(1, 2, 3), 'choices' => array(1, 2, 3),
@ -213,17 +272,27 @@ class ChoiceValidatorTest extends \PHPUnit_Framework_TestCase
'strict' => false 'strict' => false
)); ));
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(array('2', 3), $constraint)); $this->assertTrue($this->validator->isValid(array('2', 3), $constraint));
} }
public function testStrictIsTrueWhenMultipleChoices() public function testStrictWithMultipleChoices()
{ {
$constraint = new Choice(array( $constraint = new Choice(array(
'choices' => array(1, 2, 3), 'choices' => array(1, 2, 3),
'multiple' => true, 'multiple' => true,
'strict' => true 'strict' => true,
'multipleMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => '3',
));
$this->assertFalse($this->validator->isValid(array(2, '3'), $constraint)); $this->assertFalse($this->validator->isValid(array(2, '3'), $constraint));
} }
} }

View File

@ -11,6 +11,10 @@
namespace Symfony\Tests\Component\Validator\Constraints; namespace Symfony\Tests\Component\Validator\Constraints;
use Symfony\Component\Validator\GlobalExecutionContext;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Constraints\Min; use Symfony\Component\Validator\Constraints\Min;
use Symfony\Component\Validator\Constraints\NotNull; use Symfony\Component\Validator\Constraints\NotNull;
@ -21,32 +25,42 @@ use Symfony\Component\Validator\Constraints\CollectionValidator;
abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $validator;
protected $walker; protected $walker;
protected $context; protected $context;
protected $validator;
protected function setUp() protected function setUp()
{ {
$this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false); $this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false);
$metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface'); $this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->context = new ExecutionContext('Root', $this->walker, $metadataFactory);
$this->validator = new CollectionValidator(); $this->validator = new CollectionValidator();
$this->validator->initialize($this->context); $this->validator->initialize($this->context);
$this->context->expects($this->any())
->method('getGraphWalker')
->will($this->returnValue($this->walker));
$this->context->expects($this->any())
->method('getGroup')
->will($this->returnValue('MyGroup'));
$this->context->expects($this->any())
->method('getPropertyPath')
->will($this->returnValue('foo.bar'));
} }
protected function tearDown() protected function tearDown()
{ {
$this->validator = null;
$this->walker = null; $this->walker = null;
$this->context = null; $this->context = null;
$this->validator = null;
} }
abstract protected function prepareTestData(array $contents); abstract protected function prepareTestData(array $contents);
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid(null, new Collection(array('fields' => array( $this->assertTrue($this->validator->isValid(null, new Collection(array('fields' => array(
'foo' => new Min(4), 'foo' => new Min(4),
))))); )))));
@ -56,6 +70,9 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$data = $this->prepareTestData(array('foo' => 'foobar')); $data = $this->prepareTestData(array('foo' => 'foobar'));
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
'foo' => new Min(4), 'foo' => new Min(4),
)))); ))));
@ -73,52 +90,63 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
public function testWalkSingleConstraint() public function testWalkSingleConstraint()
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('foo');
$constraint = new Min(4); $constraint = new Min(4);
$array = array('foo' => 3); $array = array(
'foo' => 3,
'bar' => 5,
);
$i = 0;
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
$this->walker->expects($this->once()) $this->walker->expects($this->at($i++))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->with($constraint, $value, 'MyGroup', 'foo.bar['.$key.']');
} }
$data = $this->prepareTestData($array); $data = $this->prepareTestData($array);
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
'fields' => array( 'fields' => array(
'foo' => $constraint, 'foo' => $constraint,
'bar' => $constraint,
), ),
)))); ))));
} }
public function testWalkMultipleConstraints() public function testWalkMultipleConstraints()
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('foo');
$constraints = array( $constraints = array(
new Min(4), new Min(4),
new NotNull(), new NotNull(),
); );
$array = array('foo' => 3);
$array = array(
'foo' => 3,
'bar' => 5,
);
$i = 0;
foreach ($array as $key => $value) { foreach ($array as $key => $value) {
foreach ($constraints as $i => $constraint) { foreach ($constraints as $constraint) {
$this->walker->expects($this->at($i)) $this->walker->expects($this->at($i++))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($value), $this->equalTo('MyGroup'), $this->equalTo('foo['.$key.']')); ->with($constraint, $value, 'MyGroup', 'foo.bar['.$key.']');
} }
} }
$data = $this->prepareTestData($array); $data = $this->prepareTestData($array);
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
'fields' => array( 'fields' => array(
'foo' => $constraints, 'foo' => $constraints,
'bar' => $constraints,
) )
)))); ))));
} }
@ -127,13 +155,20 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$data = $this->prepareTestData(array( $data = $this->prepareTestData(array(
'foo' => 5, 'foo' => 5,
'bar' => 6, 'baz' => 6,
)); ));
$this->context->expects($this->once())
->method('addViolationAtSubPath')
->with('[baz]', 'myMessage', array(
'{{ field }}' => 'baz'
));
$this->assertFalse($this->validator->isValid($data, new Collection(array( $this->assertFalse($this->validator->isValid($data, new Collection(array(
'fields' => array( 'fields' => array(
'foo' => new Min(4), 'foo' => new Min(4),
), ),
'extraFieldsMessage' => 'myMessage',
)))); ))));
} }
@ -143,13 +178,17 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$data = $this->prepareTestData(array( $data = $this->prepareTestData(array(
'foo' => null, 'foo' => null,
)); ));
$collection = new Collection(array(
$constraint = new Collection(array(
'fields' => array( 'fields' => array(
'foo' => new Min(4), 'foo' => new Min(4),
), ),
)); ));
$this->assertTrue($this->validator->isValid($data, $collection)); $this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, $constraint));
} }
public function testExtraFieldsAllowed() public function testExtraFieldsAllowed()
@ -158,37 +197,55 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'foo' => 5, 'foo' => 5,
'bar' => 6, 'bar' => 6,
)); ));
$collection = new Collection(array(
$constraint = new Collection(array(
'fields' => array( 'fields' => array(
'foo' => new Min(4), 'foo' => new Min(4),
), ),
'allowExtraFields' => true, 'allowExtraFields' => true,
)); ));
$this->assertTrue($this->validator->isValid($data, $collection)); $this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, $constraint));
} }
public function testMissingFieldsDisallowed() public function testMissingFieldsDisallowed()
{ {
$data = $this->prepareTestData(array()); $data = $this->prepareTestData(array());
$this->assertFalse($this->validator->isValid($data, new Collection(array( $constraint = new Collection(array(
'fields' => array( 'fields' => array(
'foo' => new Min(4), 'foo' => new Min(4),
), ),
)))); 'missingFieldsMessage' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolationAtSubPath')
->with('[foo]', 'myMessage', array(
'{{ field }}' => 'foo',
));
$this->assertFalse($this->validator->isValid($data, $constraint));
} }
public function testMissingFieldsAllowed() public function testMissingFieldsAllowed()
{ {
$data = $this->prepareTestData(array()); $data = $this->prepareTestData(array());
$this->assertTrue($this->validator->isValid($data, new Collection(array( $constraint = new Collection(array(
'fields' => array( 'fields' => array(
'foo' => new Min(4), 'foo' => new Min(4),
), ),
'allowMissingFields' => true, 'allowMissingFields' => true,
)))); ));
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, $constraint));
} }
public function testOptionalFieldPresent() public function testOptionalFieldPresent()
@ -197,6 +254,9 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'foo' => null, 'foo' => null,
)); ));
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
'foo' => new Optional(), 'foo' => new Optional(),
)))); ))));
@ -206,6 +266,9 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$data = $this->prepareTestData(array()); $data = $this->prepareTestData(array());
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
'foo' => new Optional(), 'foo' => new Optional(),
)))); ))));
@ -213,9 +276,6 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
public function testOptionalFieldSingleConstraint() public function testOptionalFieldSingleConstraint()
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('bar');
$array = array( $array = array(
'foo' => 5, 'foo' => 5,
); );
@ -224,7 +284,10 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$this->walker->expects($this->once()) $this->walker->expects($this->once())
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($array['foo']), $this->equalTo('MyGroup'), $this->equalTo('bar[foo]')); ->with($constraint, $array['foo'], 'MyGroup', 'foo.bar[foo]');
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$data = $this->prepareTestData($array); $data = $this->prepareTestData($array);
@ -235,9 +298,6 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
public function testOptionalFieldMultipleConstraints() public function testOptionalFieldMultipleConstraints()
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('bar');
$array = array( $array = array(
'foo' => 5, 'foo' => 5,
); );
@ -250,9 +310,12 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
foreach ($constraints as $i => $constraint) { foreach ($constraints as $i => $constraint) {
$this->walker->expects($this->at($i)) $this->walker->expects($this->at($i))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($array['foo']), $this->equalTo('MyGroup'), $this->equalTo('bar[foo]')); ->with($constraint, $array['foo'], 'MyGroup', 'foo.bar[foo]');
} }
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$data = $this->prepareTestData($array); $data = $this->prepareTestData($array);
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
@ -266,6 +329,9 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
'foo' => null, 'foo' => null,
)); ));
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$this->assertTrue($this->validator->isValid($data, new Collection(array( $this->assertTrue($this->validator->isValid($data, new Collection(array(
'foo' => new Required(), 'foo' => new Required(),
)))); ))));
@ -275,16 +341,22 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
{ {
$data = $this->prepareTestData(array()); $data = $this->prepareTestData(array());
$this->context->expects($this->once())
->method('addViolationAtSubPath')
->with('[foo]', 'myMessage', array(
'{{ field }}' => 'foo',
));
$this->assertFalse($this->validator->isValid($data, new Collection(array( $this->assertFalse($this->validator->isValid($data, new Collection(array(
'foo' => new Required(), 'fields' => array(
'foo' => new Required(),
),
'missingFieldsMessage' => 'myMessage',
)))); ))));
} }
public function testRequiredFieldSingleConstraint() public function testRequiredFieldSingleConstraint()
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('bar');
$array = array( $array = array(
'foo' => 5, 'foo' => 5,
); );
@ -293,7 +365,10 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$this->walker->expects($this->once()) $this->walker->expects($this->once())
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($array['foo']), $this->equalTo('MyGroup'), $this->equalTo('bar[foo]')); ->with($constraint, $array['foo'], 'MyGroup', 'foo.bar[foo]');
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$data = $this->prepareTestData($array); $data = $this->prepareTestData($array);
@ -304,9 +379,6 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
public function testRequiredFieldMultipleConstraints() public function testRequiredFieldMultipleConstraints()
{ {
$this->context->setGroup('MyGroup');
$this->context->setPropertyPath('bar');
$array = array( $array = array(
'foo' => 5, 'foo' => 5,
); );
@ -319,9 +391,12 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
foreach ($constraints as $i => $constraint) { foreach ($constraints as $i => $constraint) {
$this->walker->expects($this->at($i)) $this->walker->expects($this->at($i))
->method('walkConstraint') ->method('walkConstraint')
->with($this->equalTo($constraint), $this->equalTo($array['foo']), $this->equalTo('MyGroup'), $this->equalTo('bar[foo]')); ->with($constraint, $array['foo'], 'MyGroup', 'foo.bar[foo]');
} }
$this->context->expects($this->never())
->method('addViolationAtSubPath');
$data = $this->prepareTestData($array); $data = $this->prepareTestData($array);
$this->assertTrue($this->validator->isValid($array, new Collection(array( $this->assertTrue($this->validator->isValid($array, new Collection(array(
@ -334,6 +409,7 @@ abstract class CollectionValidatorTest extends \PHPUnit_Framework_TestCase
$value = new \ArrayObject(array( $value = new \ArrayObject(array(
'foo' => 3 'foo' => 3
)); ));
$this->validator->isValid($value, new Collection(array( $this->validator->isValid($value, new Collection(array(
'fields' => array( 'fields' => array(
'foo' => new Min(2), 'foo' => new Min(2),

View File

@ -16,43 +16,57 @@ use Symfony\Component\Validator\Constraints\CountryValidator;
class CountryValidatorTest extends LocalizedTestCase class CountryValidatorTest extends LocalizedTestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new CountryValidator(); $this->validator = new CountryValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Country())); $this->assertTrue($this->validator->isValid(null, new Country()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Country())); $this->assertTrue($this->validator->isValid('', new Country()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Country()); $this->validator->isValid(new \stdClass(), new Country());
} }
/** /**
* @dataProvider getValidCountries * @dataProvider getValidCountries
*/ */
public function testValidCountries($date) public function testValidCountries($country)
{ {
$this->assertTrue($this->validator->isValid($date, new Country())); $this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($country, new Country()));
} }
public function getValidCountries() public function getValidCountries()
@ -67,9 +81,19 @@ class CountryValidatorTest extends LocalizedTestCase
/** /**
* @dataProvider getInvalidCountries * @dataProvider getInvalidCountries
*/ */
public function testInvalidCountries($date) public function testInvalidCountries($country)
{ {
$this->assertFalse($this->validator->isValid($date, new Country())); $constraint = new Country(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $country,
));
$this->assertFalse($this->validator->isValid($country, $constraint));
} }
public function getInvalidCountries() public function getInvalidCountries()
@ -79,17 +103,4 @@ class CountryValidatorTest extends LocalizedTestCase
array('EN'), array('EN'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Country(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,46 +16,63 @@ use Symfony\Component\Validator\Constraints\DateTimeValidator;
class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new DateTimeValidator(); $this->validator = new DateTimeValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new DateTime())); $this->assertTrue($this->validator->isValid(null, new DateTime()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new DateTime())); $this->assertTrue($this->validator->isValid('', new DateTime()));
} }
public function testDateTimeClassIsValid() public function testDateTimeClassIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(new \DateTime(), new DateTime())); $this->assertTrue($this->validator->isValid(new \DateTime(), new DateTime()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new DateTime()); $this->validator->isValid(new \stdClass(), new DateTime());
} }
/** /**
* @dataProvider getValidDateTimes * @dataProvider getValidDateTimes
*/ */
public function testValidDateTimes($date) public function testValidDateTimes($dateTime)
{ {
$this->assertTrue($this->validator->isValid($date, new DateTime())); $this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($dateTime, new DateTime()));
} }
public function getValidDateTimes() public function getValidDateTimes()
@ -70,9 +87,19 @@ class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase
/** /**
* @dataProvider getInvalidDateTimes * @dataProvider getInvalidDateTimes
*/ */
public function testInvalidDateTimes($date) public function testInvalidDateTimes($dateTime)
{ {
$this->assertFalse($this->validator->isValid($date, new DateTime())); $constraint = new DateTime(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $dateTime,
));
$this->assertFalse($this->validator->isValid($dateTime, $constraint));
} }
public function getInvalidDateTimes() public function getInvalidDateTimes()
@ -90,17 +117,4 @@ class DateTimeValidatorTest extends \PHPUnit_Framework_TestCase
array('2010-01-01 00:00:60'), array('2010-01-01 00:00:60'),
); );
} }
public function testMessageIsSet()
{
$constraint = new DateTime(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,37 +16,51 @@ use Symfony\Component\Validator\Constraints\DateValidator;
class DateValidatorTest extends \PHPUnit_Framework_TestCase class DateValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new DateValidator(); $this->validator = new DateValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Date())); $this->assertTrue($this->validator->isValid(null, new Date()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Date())); $this->assertTrue($this->validator->isValid('', new Date()));
} }
public function testDateTimeClassIsValid() public function testDateTimeClassIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(new \DateTime(), new Date())); $this->assertTrue($this->validator->isValid(new \DateTime(), new Date()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Date()); $this->validator->isValid(new \stdClass(), new Date());
} }
@ -55,6 +69,9 @@ class DateValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidDates($date) public function testValidDates($date)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($date, new Date())); $this->assertTrue($this->validator->isValid($date, new Date()));
} }
@ -72,7 +89,17 @@ class DateValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidDates($date) public function testInvalidDates($date)
{ {
$this->assertFalse($this->validator->isValid($date, new Date())); $constraint = new Date(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $date,
));
$this->assertFalse($this->validator->isValid($date, $constraint));
} }
public function getInvalidDates() public function getInvalidDates()
@ -86,17 +113,4 @@ class DateValidatorTest extends \PHPUnit_Framework_TestCase
array('2010-02-29'), array('2010-02-29'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Date(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,32 +16,43 @@ use Symfony\Component\Validator\Constraints\EmailValidator;
class EmailValidatorTest extends \PHPUnit_Framework_TestCase class EmailValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new EmailValidator(); $this->validator = new EmailValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Email())); $this->assertTrue($this->validator->isValid(null, new Email()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Email())); $this->assertTrue($this->validator->isValid('', new Email()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Email()); $this->validator->isValid(new \stdClass(), new Email());
} }
@ -50,6 +61,9 @@ class EmailValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidEmails($email) public function testValidEmails($email)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($email, new Email())); $this->assertTrue($this->validator->isValid($email, new Email()));
} }
@ -67,7 +81,17 @@ class EmailValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidEmails($email) public function testInvalidEmails($email)
{ {
$this->assertFalse($this->validator->isValid($email, new Email())); $constraint = new Email(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $email,
));
$this->assertFalse($this->validator->isValid($email, $constraint));
} }
public function getInvalidEmails() public function getInvalidEmails()
@ -79,17 +103,4 @@ class EmailValidatorTest extends \PHPUnit_Framework_TestCase
array('example@example.com@example.com'), array('example@example.com@example.com'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Email(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,25 +16,35 @@ use Symfony\Component\Validator\Constraints\FalseValidator;
class FalseValidatorTest extends \PHPUnit_Framework_TestCase class FalseValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new FalseValidator(); $this->validator = new FalseValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new False())); $this->assertTrue($this->validator->isValid(null, new False()));
} }
public function testFalseIsValid() public function testFalseIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(false, new False())); $this->assertTrue($this->validator->isValid(false, new False()));
} }
@ -44,8 +54,10 @@ class FalseValidatorTest extends \PHPUnit_Framework_TestCase
'message' => 'myMessage' 'message' => 'myMessage'
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array());
$this->assertFalse($this->validator->isValid(true, $constraint)); $this->assertFalse($this->validator->isValid(true, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array());
} }
} }

View File

@ -0,0 +1,22 @@
<?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\Tests\Component\Validator\Constraints;
use Symfony\Component\HttpFoundation\File\File;
class FileValidatorObjectTest extends FileValidatorTest
{
protected function getFile($filename)
{
return new File($filename);
}
}

View File

@ -0,0 +1,37 @@
<?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\Tests\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraints\File;
class FileValidatorPathTest extends FileValidatorTest
{
protected function getFile($filename)
{
return $filename;
}
public function testFileNotFound()
{
$constraint = new File(array(
'notFoundMessage' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ file }}' => 'foobar',
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
}
}

View File

@ -16,15 +16,18 @@ use Symfony\Component\Validator\Constraints\FileValidator;
use Symfony\Component\HttpFoundation\File\File as FileObject; use Symfony\Component\HttpFoundation\File\File as FileObject;
use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\UploadedFile;
class FileValidatorTest extends \PHPUnit_Framework_TestCase abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected $path; protected $path;
protected $file; protected $file;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new FileValidator(); $this->validator = new FileValidator();
$this->validator->initialize($this->context);
$this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'FileValidatorTest'; $this->path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'FileValidatorTest';
$this->file = fopen($this->path, 'w'); $this->file = fopen($this->path, 'w');
} }
@ -33,6 +36,7 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
{ {
fclose($this->file); fclose($this->file);
$this->context = null;
$this->validator = null; $this->validator = null;
$this->path = null; $this->path = null;
$this->file = null; $this->file = null;
@ -40,11 +44,17 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new File())); $this->assertTrue($this->validator->isValid(null, new File()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new File())); $this->assertTrue($this->validator->isValid('', new File()));
} }
@ -58,11 +68,17 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidFile() public function testValidFile()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($this->path, new File())); $this->assertTrue($this->validator->isValid($this->path, new File()));
} }
public function testValidUploadedfile() public function testValidUploadedfile()
{ {
$this->context->expects($this->never())
->method('addViolation');
$file = new UploadedFile($this->path, 'originalName'); $file = new UploadedFile($this->path, 'originalName');
$this->assertTrue($this->validator->isValid($file, new File())); $this->assertTrue($this->validator->isValid($file, new File()));
} }
@ -76,13 +92,15 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
'maxSizeMessage' => 'myMessage', 'maxSizeMessage' => 'myMessage',
)); ));
$this->assertFileValid($this->path, $constraint, false); $this->context->expects($this->once())
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); ->method('addViolation')
$this->assertEquals($this->validator->getMessageParameters(), array( ->with('myMessage', array(
'{{ limit }}' => '10 bytes', '{{ limit }}' => '10 bytes',
'{{ size }}' => '11 bytes', '{{ size }}' => '11 bytes',
'{{ file }}' => $this->path, '{{ file }}' => $this->path,
)); ));
$this->assertFalse($this->validator->isValid($this->getFile($this->path), $constraint));
} }
public function testTooLargeKiloBytes() public function testTooLargeKiloBytes()
@ -94,13 +112,15 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
'maxSizeMessage' => 'myMessage', 'maxSizeMessage' => 'myMessage',
)); ));
$this->assertFileValid($this->path, $constraint, false); $this->context->expects($this->once())
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); ->method('addViolation')
$this->assertEquals($this->validator->getMessageParameters(), array( ->with('myMessage', array(
'{{ limit }}' => '1 kB', '{{ limit }}' => '1 kB',
'{{ size }}' => '1.4 kB', '{{ size }}' => '1.4 kB',
'{{ file }}' => $this->path, '{{ file }}' => $this->path,
)); ));
$this->assertFalse($this->validator->isValid($this->getFile($this->path), $constraint));
} }
public function testTooLargeMegaBytes() public function testTooLargeMegaBytes()
@ -112,13 +132,15 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
'maxSizeMessage' => 'myMessage', 'maxSizeMessage' => 'myMessage',
)); ));
$this->assertFileValid($this->path, $constraint, false); $this->context->expects($this->once())
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); ->method('addViolation')
$this->assertEquals($this->validator->getMessageParameters(), array( ->with('myMessage', array(
'{{ limit }}' => '1 MB', '{{ limit }}' => '1 MB',
'{{ size }}' => '1.4 MB', '{{ size }}' => '1.4 MB',
'{{ file }}' => $this->path, '{{ file }}' => $this->path,
)); ));
$this->assertFalse($this->validator->isValid($this->getFile($this->path), $constraint));
} }
/** /**
@ -133,19 +155,6 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
$this->validator->isValid($this->path, $constraint); $this->validator->isValid($this->path, $constraint);
} }
public function testFileNotFound()
{
$constraint = new File(array(
'notFoundMessage' => 'myMessage',
));
$this->assertFileValid('foobar', $constraint, false);
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ file }}' => 'foobar',
));
}
public function testValidMimeType() public function testValidMimeType()
{ {
$file = $this $file = $this
@ -164,6 +173,9 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue('image/jpg')) ->will($this->returnValue('image/jpg'))
; ;
$this->context->expects($this->never())
->method('addViolation');
$constraint = new File(array( $constraint = new File(array(
'mimeTypes' => array('image/png', 'image/jpg'), 'mimeTypes' => array('image/png', 'image/jpg'),
)); ));
@ -189,6 +201,9 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue('image/jpg')) ->will($this->returnValue('image/jpg'))
; ;
$this->context->expects($this->never())
->method('addViolation');
$constraint = new File(array( $constraint = new File(array(
'mimeTypes' => array('image/*'), 'mimeTypes' => array('image/*'),
)); ));
@ -219,13 +234,15 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
'mimeTypesMessage' => 'myMessage', 'mimeTypesMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ type }}' => '"application/pdf"',
'{{ types }}' => '"image/png", "image/jpg"',
'{{ file }}' => $this->path,
));
$this->assertFalse($this->validator->isValid($file, $constraint)); $this->assertFalse($this->validator->isValid($file, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ type }}' => '"application/pdf"',
'{{ types }}' => '"image/png", "image/jpg"',
'{{ file }}' => $this->path,
));
} }
public function testInvalidWildcardMimeType() public function testInvalidWildcardMimeType()
@ -251,35 +268,40 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
'mimeTypesMessage' => 'myMessage', 'mimeTypesMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ type }}' => '"application/pdf"',
'{{ types }}' => '"image/*", "image/jpg"',
'{{ file }}' => $this->path,
));
$this->assertFalse($this->validator->isValid($file, $constraint)); $this->assertFalse($this->validator->isValid($file, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ type }}' => '"application/pdf"',
'{{ types }}' => '"image/*", "image/jpg"',
'{{ file }}' => $this->path,
));
} }
/** /**
* @dataProvider uploadedFileErrorProvider * @dataProvider uploadedFileErrorProvider
*/ */
public function testUploadedFileError($error, $message) public function testUploadedFileError($error, $message, array $params = array())
{ {
$file = new UploadedFile('/path/to/file', 'originalName', 'mime', 0, $error); $file = new UploadedFile('/path/to/file', 'originalName', 'mime', 0, $error);
$options[$message] = 'myMessage'; $constraint = new File(array(
$message => 'myMessage',
));
$constraint = new File($options); $this->context->expects($this->once())
->method('addViolation')
->with('myMessage', $params);
$this->assertFalse($this->validator->isValid($file, $constraint)); $this->assertFalse($this->validator->isValid($file, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
} }
public function uploadedFileErrorProvider() public function uploadedFileErrorProvider()
{ {
return array( return array(
array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage'), array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array('{{ limit }}' => UploadedFile::getMaxFilesize() . ' bytes')),
array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'), array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'),
array(UPLOAD_ERR_PARTIAL, 'uploadErrorMessage'), array(UPLOAD_ERR_PARTIAL, 'uploadErrorMessage'),
array(UPLOAD_ERR_NO_TMP_DIR, 'uploadErrorMessage'), array(UPLOAD_ERR_NO_TMP_DIR, 'uploadErrorMessage'),
@ -287,11 +309,5 @@ class FileValidatorTest extends \PHPUnit_Framework_TestCase
); );
} }
protected function assertFileValid($filename, File $constraint, $valid = true) abstract protected function getFile($filename);
{
$this->assertEquals($this->validator->isValid($filename, $constraint), $valid);
if (file_exists($filename)) {
$this->assertEquals($this->validator->isValid(new FileObject($filename), $constraint), $valid);
}
}
} }

View File

@ -16,33 +16,48 @@ use Symfony\Component\Validator\Constraints\ImageValidator;
class ImageValidatorTest extends \PHPUnit_Framework_TestCase class ImageValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected $path; protected $path;
protected $image; protected $image;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new ImageValidator(); $this->validator = new ImageValidator();
$this->validator->initialize($this->context);
$this->image = __DIR__.'/Fixtures/test.gif'; $this->image = __DIR__.'/Fixtures/test.gif';
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Image())); $this->assertTrue($this->validator->isValid(null, new Image()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Image())); $this->assertTrue($this->validator->isValid('', new Image()));
} }
public function testValidImage() public function testValidImage()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($this->image, new Image())); $this->assertTrue($this->validator->isValid($this->image, new Image()));
} }
public function testValidSize() public function testValidSize()
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Image(array( $constraint = new Image(array(
'minWidth' => 1, 'minWidth' => 1,
'maxWidth' => 2, 'maxWidth' => 2,
@ -60,12 +75,14 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
'minWidthMessage' => 'myMessage', 'minWidthMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ width }}' => '2',
'{{ min_width }}' => '3',
));
$this->assertFalse($this->validator->isValid($this->image, $constraint)); $this->assertFalse($this->validator->isValid($this->image, $constraint));
$this->assertEquals('myMessage', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ width }}' => '2',
'{{ min_width }}' => '3',
), $this->validator->getMessageParameters());
} }
public function testWidthTooBig() public function testWidthTooBig()
@ -75,12 +92,14 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
'maxWidthMessage' => 'myMessage', 'maxWidthMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ width }}' => '2',
'{{ max_width }}' => '1',
));
$this->assertFalse($this->validator->isValid($this->image, $constraint)); $this->assertFalse($this->validator->isValid($this->image, $constraint));
$this->assertEquals('myMessage', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ width }}' => '2',
'{{ max_width }}' => '1',
), $this->validator->getMessageParameters());
} }
public function testHeightTooSmall() public function testHeightTooSmall()
@ -90,12 +109,14 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
'minHeightMessage' => 'myMessage', 'minHeightMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ height }}' => '2',
'{{ min_height }}' => '3',
));
$this->assertFalse($this->validator->isValid($this->image, $constraint)); $this->assertFalse($this->validator->isValid($this->image, $constraint));
$this->assertEquals('myMessage', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ height }}' => '2',
'{{ min_height }}' => '3',
), $this->validator->getMessageParameters());
} }
public function testHeightTooBig() public function testHeightTooBig()
@ -105,12 +126,14 @@ class ImageValidatorTest extends \PHPUnit_Framework_TestCase
'maxHeightMessage' => 'myMessage', 'maxHeightMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ height }}' => '2',
'{{ max_height }}' => '1',
));
$this->assertFalse($this->validator->isValid($this->image, $constraint)); $this->assertFalse($this->validator->isValid($this->image, $constraint));
$this->assertEquals('myMessage', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ height }}' => '2',
'{{ max_height }}' => '1',
), $this->validator->getMessageParameters());
} }
/** /**

View File

@ -16,39 +16,51 @@ use Symfony\Component\Validator\Constraints\IpValidator;
class IpValidatorTest extends \PHPUnit_Framework_TestCase class IpValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new IpValidator(); $this->validator = new IpValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Ip())); $this->assertTrue($this->validator->isValid(null, new Ip()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Ip())); $this->assertTrue($this->validator->isValid('', new Ip()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Ip()); $this->validator->isValid(new \stdClass(), new Ip());
} }
/**
* @expectedException Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidValidatorVersion() public function testInvalidValidatorVersion()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
$ip = new Ip(array( $ip = new Ip(array(
'version' => 666, 'version' => 666,
)); ));
@ -59,6 +71,9 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidIpsV4($ip) public function testValidIpsV4($ip)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($ip, new Ip(array( $this->assertTrue($this->validator->isValid($ip, new Ip(array(
'version' => Ip::V4, 'version' => Ip::V4,
)))); ))));
@ -83,6 +98,9 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidIpsV6($ip) public function testValidIpsV6($ip)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($ip, new Ip(array( $this->assertTrue($this->validator->isValid($ip, new Ip(array(
'version' => Ip::V6, 'version' => Ip::V6,
)))); ))));
@ -118,6 +136,9 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidIpsAll($ip) public function testValidIpsAll($ip)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($ip, new Ip(array( $this->assertTrue($this->validator->isValid($ip, new Ip(array(
'version' => Ip::ALL, 'version' => Ip::ALL,
)))); ))));
@ -133,9 +154,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidIpsV4($ip) public function testInvalidIpsV4($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V4, 'version' => Ip::V4,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidIpsV4() public function getInvalidIpsV4()
@ -158,9 +188,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidPrivateIpsV4($ip) public function testInvalidPrivateIpsV4($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V4_NO_PRIV, 'version' => Ip::V4_NO_PRIV,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidPrivateIpsV4() public function getInvalidPrivateIpsV4()
@ -177,9 +216,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidReservedIpsV4($ip) public function testInvalidReservedIpsV4($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V4_NO_RES, 'version' => Ip::V4_NO_RES,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidReservedIpsV4() public function getInvalidReservedIpsV4()
@ -196,9 +244,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidPublicIpsV4($ip) public function testInvalidPublicIpsV4($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V4_ONLY_PUBLIC, 'version' => Ip::V4_ONLY_PUBLIC,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidPublicIpsV4() public function getInvalidPublicIpsV4()
@ -211,9 +268,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidIpsV6($ip) public function testInvalidIpsV6($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V6, 'version' => Ip::V6,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidIpsV6() public function getInvalidIpsV6()
@ -240,9 +306,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidPrivateIpsV6($ip) public function testInvalidPrivateIpsV6($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V6_NO_PRIV, 'version' => Ip::V6_NO_PRIV,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidPrivateIpsV6() public function getInvalidPrivateIpsV6()
@ -259,9 +334,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidReservedIpsV6($ip) public function testInvalidReservedIpsV6($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V6_NO_RES, 'version' => Ip::V6_NO_RES,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidReservedIpsV6() public function getInvalidReservedIpsV6()
@ -277,9 +361,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidPublicIpsV6($ip) public function testInvalidPublicIpsV6($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::V6_ONLY_PUBLIC, 'version' => Ip::V6_ONLY_PUBLIC,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidPublicIpsV6() public function getInvalidPublicIpsV6()
@ -292,9 +385,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidIpsAll($ip) public function testInvalidIpsAll($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::ALL, 'version' => Ip::ALL,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidIpsAll() public function getInvalidIpsAll()
@ -307,9 +409,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidPrivateIpsAll($ip) public function testInvalidPrivateIpsAll($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::ALL_NO_PRIV, 'version' => Ip::ALL_NO_PRIV,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidPrivateIpsAll() public function getInvalidPrivateIpsAll()
@ -322,9 +433,18 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidReservedIpsAll($ip) public function testInvalidReservedIpsAll($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::ALL_NO_RES, 'version' => Ip::ALL_NO_RES,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidReservedIpsAll() public function getInvalidReservedIpsAll()
@ -337,26 +457,22 @@ class IpValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidPublicIpsAll($ip) public function testInvalidPublicIpsAll($ip)
{ {
$this->assertFalse($this->validator->isValid($ip, new Ip(array( $constraint = new Ip(array(
'version' => Ip::ALL_ONLY_PUBLIC, 'version' => Ip::ALL_ONLY_PUBLIC,
)))); 'message' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $ip,
));
$this->assertFalse($this->validator->isValid($ip, $constraint));
} }
public function getInvalidPublicIpsAll() public function getInvalidPublicIpsAll()
{ {
return array_merge($this->getInvalidPublicIpsV4(), $this->getInvalidPublicIpsV6()); return array_merge($this->getInvalidPublicIpsV4(), $this->getInvalidPublicIpsV6());
} }
public function testMessageIsSet()
{
$constraint = new Ip(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,43 +16,57 @@ use Symfony\Component\Validator\Constraints\LanguageValidator;
class LanguageValidatorTest extends LocalizedTestCase class LanguageValidatorTest extends LocalizedTestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new LanguageValidator(); $this->validator = new LanguageValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Language())); $this->assertTrue($this->validator->isValid(null, new Language()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Language())); $this->assertTrue($this->validator->isValid('', new Language()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Language()); $this->validator->isValid(new \stdClass(), new Language());
} }
/** /**
* @dataProvider getValidLanguages * @dataProvider getValidLanguages
*/ */
public function testValidLanguages($date) public function testValidLanguages($language)
{ {
$this->assertTrue($this->validator->isValid($date, new Language())); $this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($language, new Language()));
} }
public function getValidLanguages() public function getValidLanguages()
@ -67,9 +81,19 @@ class LanguageValidatorTest extends LocalizedTestCase
/** /**
* @dataProvider getInvalidLanguages * @dataProvider getInvalidLanguages
*/ */
public function testInvalidLanguages($date) public function testInvalidLanguages($language)
{ {
$this->assertFalse($this->validator->isValid($date, new Language())); $constraint = new Language(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $language,
));
$this->assertFalse($this->validator->isValid($language, $constraint));
} }
public function getInvalidLanguages() public function getInvalidLanguages()
@ -79,17 +103,4 @@ class LanguageValidatorTest extends LocalizedTestCase
array('foobar'), array('foobar'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Language(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,43 +16,57 @@ use Symfony\Component\Validator\Constraints\LocaleValidator;
class LocaleValidatorTest extends LocalizedTestCase class LocaleValidatorTest extends LocalizedTestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
parent::setUp(); parent::setUp();
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new LocaleValidator(); $this->validator = new LocaleValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Locale())); $this->assertTrue($this->validator->isValid(null, new Locale()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Locale())); $this->assertTrue($this->validator->isValid('', new Locale()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Locale()); $this->validator->isValid(new \stdClass(), new Locale());
} }
/** /**
* @dataProvider getValidLocales * @dataProvider getValidLocales
*/ */
public function testValidLocales($date) public function testValidLocales($locale)
{ {
$this->assertTrue($this->validator->isValid($date, new Locale())); $this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($locale, new Locale()));
} }
public function getValidLocales() public function getValidLocales()
@ -68,9 +82,19 @@ class LocaleValidatorTest extends LocalizedTestCase
/** /**
* @dataProvider getInvalidLocales * @dataProvider getInvalidLocales
*/ */
public function testInvalidLocales($date) public function testInvalidLocales($locale)
{ {
$this->assertFalse($this->validator->isValid($date, new Locale())); $constraint = new Locale(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $locale,
));
$this->assertFalse($this->validator->isValid($locale, $constraint));
} }
public function getInvalidLocales() public function getInvalidLocales()
@ -80,17 +104,4 @@ class LocaleValidatorTest extends LocalizedTestCase
array('foobar'), array('foobar'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Locale(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,44 +16,60 @@ use Symfony\Component\Validator\Constraints\MaxLengthValidator;
class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MaxLengthValidator(); $this->validator = new MaxLengthValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new MaxLength(array('limit' => 5)))); $this->assertTrue($this->validator->isValid(null, new MaxLength(array('limit' => 5))));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new MaxLength(array('limit' => 5)))); $this->assertTrue($this->validator->isValid('', new MaxLength(array('limit' => 5))));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new MaxLength(array('limit' => 5))); $this->validator->isValid(new \stdClass(), new MaxLength(array('limit' => 5)));
} }
/** /**
* @dataProvider getValidValues * @dataProvider getValidValues
*/ */
public function testValidValues($value, $skip = false) public function testValidValues($value, $mbOnly = false)
{ {
if (!$skip) { if ($mbOnly && !function_exists('mb_strlen')) {
$constraint = new MaxLength(array('limit' => 5)); return $this->markTestSkipped('mb_strlen does not exist');
$this->assertTrue($this->validator->isValid($value, $constraint));
} }
$this->context->expects($this->never())
->method('addViolation');
$constraint = new MaxLength(array('limit' => 5));
$this->assertTrue($this->validator->isValid($value, $constraint));
} }
public function getValidValues() public function getValidValues()
@ -61,20 +77,33 @@ class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
return array( return array(
array(12345), array(12345),
array('12345'), array('12345'),
array('üüüüü', !function_exists('mb_strlen')), array('üüüüü', true),
array('ééééé', !function_exists('mb_strlen')), array('ééééé', true),
); );
} }
/** /**
* @dataProvider getInvalidValues * @dataProvider getInvalidValues
*/ */
public function testInvalidValues($value, $skip = false) public function testInvalidValues($value, $mbOnly = false)
{ {
if (!$skip) { if ($mbOnly && !function_exists('mb_strlen')) {
$constraint = new MaxLength(array('limit' => 5)); return $this->markTestSkipped('mb_strlen does not exist');
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
$constraint = new MaxLength(array(
'limit' => 5,
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
'{{ limit }}' => 5,
));
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
public function getInvalidValues() public function getInvalidValues()
@ -82,26 +111,11 @@ class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
return array( return array(
array(123456), array(123456),
array('123456'), array('123456'),
array('üüüüüü', !function_exists('mb_strlen')), array('üüüüüü', true),
array('éééééé', !function_exists('mb_strlen')), array('éééééé', true),
); );
} }
public function testMessageIsSet()
{
$constraint = new MaxLength(array(
'limit' => 5,
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('123456', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => '123456',
'{{ limit }}' => 5,
));
}
public function testConstraintGetDefaultOption() public function testConstraintGetDefaultOption()
{ {
$constraint = new MaxLength(array( $constraint = new MaxLength(array(

View File

@ -16,20 +16,27 @@ use Symfony\Component\Validator\Constraints\MaxValidator;
class MaxValidatorTest extends \PHPUnit_Framework_TestCase class MaxValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MaxValidator(); $this->validator = new MaxValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Max(array('limit' => 10)))); $this->assertTrue($this->validator->isValid(null, new Max(array('limit' => 10))));
} }
@ -38,6 +45,9 @@ class MaxValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($value) public function testValidValues($value)
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Max(array('limit' => 10)); $constraint = new Max(array('limit' => 10));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
} }
@ -57,7 +67,19 @@ class MaxValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value) public function testInvalidValues($value)
{ {
$constraint = new Max(array('limit' => 10)); $constraint = new Max(array(
'limit' => 10,
'message' => 'myMessage',
'invalidMessage' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
'{{ limit }}' => 10,
));
$this->assertFalse($this->validator->isValid($value, $constraint)); $this->assertFalse($this->validator->isValid($value, $constraint));
} }
@ -70,21 +92,6 @@ class MaxValidatorTest extends \PHPUnit_Framework_TestCase
); );
} }
public function testMessageIsSet()
{
$constraint = new Max(array(
'limit' => 10,
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid(11, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 11,
'{{ limit }}' => 10,
));
}
public function testConstraintGetDefaultOption() public function testConstraintGetDefaultOption()
{ {
$constraint = new Max(array( $constraint = new Max(array(

View File

@ -16,44 +16,60 @@ use Symfony\Component\Validator\Constraints\MinLengthValidator;
class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MinLengthValidator(); $this->validator = new MinLengthValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new MinLength(array('limit' => 6)))); $this->assertTrue($this->validator->isValid(null, new MinLength(array('limit' => 6))));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new MinLength(array('limit' => 6)))); $this->assertTrue($this->validator->isValid('', new MinLength(array('limit' => 6))));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new MinLength(array('limit' => 5))); $this->validator->isValid(new \stdClass(), new MinLength(array('limit' => 5)));
} }
/** /**
* @dataProvider getValidValues * @dataProvider getValidValues
*/ */
public function testValidValues($value, $skip = false) public function testValidValues($value, $mbOnly = false)
{ {
if (!$skip) { if ($mbOnly && !function_exists('mb_strlen')) {
$constraint = new MinLength(array('limit' => 6)); return $this->markTestSkipped('mb_strlen does not exist');
$this->assertTrue($this->validator->isValid($value, $constraint));
} }
$this->context->expects($this->never())
->method('addViolation');
$constraint = new MinLength(array('limit' => 6));
$this->assertTrue($this->validator->isValid($value, $constraint));
} }
public function getValidValues() public function getValidValues()
@ -61,47 +77,45 @@ class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase
return array( return array(
array(123456), array(123456),
array('123456'), array('123456'),
array('üüüüüü', !function_exists('mb_strlen')), array('üüüüüü', true),
array('éééééé', !function_exists('mb_strlen')), array('éééééé', true),
); );
} }
/** /**
* @dataProvider getInvalidValues * @dataProvider getInvalidValues
*/ */
public function testInvalidValues($value, $skip = false) public function testInvalidValues($value, $mbOnly = false)
{ {
if (!$skip) { if ($mbOnly && !function_exists('mb_strlen')) {
$constraint = new MinLength(array('limit' => 6)); return $this->markTestSkipped('mb_strlen does not exist');
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
$constraint = new MinLength(array(
'limit' => 5,
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
'{{ limit }}' => 5,
));
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
public function getInvalidValues() public function getInvalidValues()
{ {
return array( return array(
array(12345), array(1234),
array('12345'), array('1234'),
array('üüüüü', !function_exists('mb_strlen')), array('üüüü', true),
array('ééééé', !function_exists('mb_strlen')), array('éééé', true),
); );
} }
public function testMessageIsSet()
{
$constraint = new MinLength(array(
'limit' => 5,
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('1234', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => '1234',
'{{ limit }}' => 5,
));
}
public function testConstraintGetDefaultOption() public function testConstraintGetDefaultOption()
{ {
$constraint = new MinLength(array( $constraint = new MinLength(array(

View File

@ -16,15 +16,21 @@ use Symfony\Component\Validator\Constraints\MinValidator;
class MinValidatorTest extends \PHPUnit_Framework_TestCase class MinValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MinValidator(); $this->validator = new MinValidator();
$this->validator->initialize($this->context);
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Min(array('limit' => 10)))); $this->assertTrue($this->validator->isValid(null, new Min(array('limit' => 10))));
} }
@ -33,6 +39,9 @@ class MinValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($value) public function testValidValues($value)
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Min(array('limit' => 10)); $constraint = new Min(array('limit' => 10));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
} }
@ -52,7 +61,19 @@ class MinValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value) public function testInvalidValues($value)
{ {
$constraint = new Min(array('limit' => 10)); $constraint = new Min(array(
'limit' => 10,
'message' => 'myMessage',
'invalidMessage' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
'{{ limit }}' => 10,
));
$this->assertFalse($this->validator->isValid($value, $constraint)); $this->assertFalse($this->validator->isValid($value, $constraint));
} }
@ -65,21 +86,6 @@ class MinValidatorTest extends \PHPUnit_Framework_TestCase
); );
} }
public function testMessageIsSet()
{
$constraint = new Min(array(
'limit' => 10,
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid(9, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 9,
'{{ limit }}' => 10,
));
}
public function testConstraintGetDefaultOption() public function testConstraintGetDefaultOption()
{ {
$constraint = new Min(array( $constraint = new Min(array(

View File

@ -16,15 +16,19 @@ use Symfony\Component\Validator\Constraints\NotBlankValidator;
class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new NotBlankValidator(); $this->validator = new NotBlankValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
@ -33,6 +37,9 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($date) public function testValidValues($date)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($date, new NotBlank())); $this->assertTrue($this->validator->isValid($date, new NotBlank()));
} }
@ -49,33 +56,54 @@ class NotBlankValidatorTest extends \PHPUnit_Framework_TestCase
public function testNullIsInvalid() public function testNullIsInvalid()
{ {
$this->assertFalse($this->validator->isValid(null, new NotBlank())); $constraint = new NotBlank(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage');
$this->assertFalse($this->validator->isValid(null, $constraint));
} }
public function testBlankIsInvalid() public function testBlankIsInvalid()
{
$this->assertFalse($this->validator->isValid('', new NotBlank()));
}
public function testFalseIsInvalid()
{
$this->assertFalse($this->validator->isValid(false, new NotBlank()));
}
public function testEmptyArrayIsInvalid()
{
$this->assertFalse($this->validator->isValid(array(), new NotBlank()));
}
public function testSetMessage()
{ {
$constraint = new NotBlank(array( $constraint = new NotBlank(array(
'message' => 'myMessage' 'message' => 'myMessage'
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage');
$this->assertFalse($this->validator->isValid('', $constraint)); $this->assertFalse($this->validator->isValid('', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage'); }
$this->assertEquals($this->validator->getMessageParameters(), array());
public function testFalseIsInvalid()
{
$constraint = new NotBlank(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage');
$this->assertFalse($this->validator->isValid(false, $constraint));
}
public function testEmptyArrayIsInvalid()
{
$constraint = new NotBlank(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage');
$this->assertFalse($this->validator->isValid(array(), $constraint));
} }
} }

View File

@ -16,15 +16,19 @@ use Symfony\Component\Validator\Constraints\NotNullValidator;
class NotNullValidatorTest extends \PHPUnit_Framework_TestCase class NotNullValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new NotNullValidator(); $this->validator = new NotNullValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
@ -33,6 +37,9 @@ class NotNullValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($value) public function testValidValues($value)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($value, new NotNull())); $this->assertTrue($this->validator->isValid($value, new NotNull()));
} }
@ -52,8 +59,11 @@ class NotNullValidatorTest extends \PHPUnit_Framework_TestCase
'message' => 'myMessage' 'message' => 'myMessage'
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
));
$this->assertFalse($this->validator->isValid(null, $constraint)); $this->assertFalse($this->validator->isValid(null, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array());
} }
} }

View File

@ -16,20 +16,27 @@ use Symfony\Component\Validator\Constraints\NullValidator;
class NullValidatorTest extends \PHPUnit_Framework_TestCase class NullValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new NullValidator(); $this->validator = new NullValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Null())); $this->assertTrue($this->validator->isValid(null, new Null()));
} }
@ -38,7 +45,17 @@ class NullValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value) public function testInvalidValues($value)
{ {
$this->assertFalse($this->validator->isValid($value, new Null())); $constraint = new Null(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
));
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
public function getInvalidValues() public function getInvalidValues()
@ -50,17 +67,4 @@ class NullValidatorTest extends \PHPUnit_Framework_TestCase
array(''), array(''),
); );
} }
public function testSetMessage()
{
$constraint = new Null(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid(1, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 1,
));
}
} }

View File

@ -16,32 +16,43 @@ use Symfony\Component\Validator\Constraints\RegexValidator;
class RegexValidatorTest extends \PHPUnit_Framework_TestCase class RegexValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new RegexValidator(); $this->validator = new RegexValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Regex(array('pattern' => '/^[0-9]+$/')))); $this->assertTrue($this->validator->isValid(null, new Regex(array('pattern' => '/^[0-9]+$/'))));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Regex(array('pattern' => '/^[0-9]+$/')))); $this->assertTrue($this->validator->isValid('', new Regex(array('pattern' => '/^[0-9]+$/'))));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/'))); $this->validator->isValid(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/')));
} }
@ -50,6 +61,9 @@ class RegexValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($value) public function testValidValues($value)
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Regex(array('pattern' => '/^[0-9]+$/')); $constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
} }
@ -69,7 +83,17 @@ class RegexValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value) public function testInvalidValues($value)
{ {
$constraint = new Regex(array('pattern' => '/^[0-9]+$/')); $constraint = new Regex(array(
'pattern' => '/^[0-9]+$/',
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $value,
));
$this->assertFalse($this->validator->isValid($value, $constraint)); $this->assertFalse($this->validator->isValid($value, $constraint));
} }
@ -81,20 +105,6 @@ class RegexValidatorTest extends \PHPUnit_Framework_TestCase
); );
} }
public function testMessageIsSet()
{
$constraint = new Regex(array(
'pattern' => '/^[0-9]+$/',
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
public function testConstraintGetDefaultOption() public function testConstraintGetDefaultOption()
{ {
$constraint = new Regex(array( $constraint = new Regex(array(

View File

@ -2,12 +2,12 @@
/* /*
* This file is part of the Symfony package. * This file is part of the Symfony package.
* *
* (c) Fabien Potencier <fabien@symfony.com> * (c) Fabien Potencier <fabien@symfony.com>
* *
* For the full copyright and license information, please view the LICENSE * For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code. * file that was distributed with this source code.
*/ */
namespace Symfony\Tests\Component\Validator\Constraints; namespace Symfony\Tests\Component\Validator\Constraints;
@ -16,44 +16,60 @@ use Symfony\Component\Validator\Constraints\SizeLengthValidator;
class SizeLengthValidatorTest extends \PHPUnit_Framework_TestCase class SizeLengthValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new SizeLengthValidator(); $this->validator = new SizeLengthValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new SizeLength(array('min' => 6, 'max' => 10)))); $this->assertTrue($this->validator->isValid(null, new SizeLength(array('min' => 6, 'max' => 10))));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new SizeLength(array('min' => 6, 'max' => 10)))); $this->assertTrue($this->validator->isValid('', new SizeLength(array('min' => 6, 'max' => 10))));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new SizeLength(array('min' => 6, 'max' => 10))); $this->validator->isValid(new \stdClass(), new SizeLength(array('min' => 6, 'max' => 10)));
} }
/** /**
* @dataProvider getValidValues * @dataProvider getValidValues
*/ */
public function testValidValues($value, $skip = false) public function testValidValues($value, $mbOnly = false)
{ {
if (!$skip) { if ($mbOnly && !function_exists('mb_strlen')) {
$constraint = new SizeLength(array('min' => 6, 'max' => 10)); return $this->markTestSkipped('mb_strlen does not exist');
$this->assertTrue($this->validator->isValid($value, $constraint));
} }
$this->context->expects($this->never())
->method('addViolation');
$constraint = new SizeLength(array('min' => 6, 'max' => 10));
$this->assertTrue($this->validator->isValid($value, $constraint));
} }
public function getValidValues() public function getValidValues()
@ -63,22 +79,27 @@ class SizeLengthValidatorTest extends \PHPUnit_Framework_TestCase
array(1234567890), array(1234567890),
array('123456'), array('123456'),
array('1234567890'), array('1234567890'),
array('üüüüüü', !function_exists('mb_strlen')), array('üüüüüü', true),
array('üüüüüüüüüü', !function_exists('mb_strlen')), array('üüüüüüüüüü', true),
array('éééééé', !function_exists('mb_strlen')), array('éééééé', true),
array('éééééééééé', !function_exists('mb_strlen')), array('éééééééééé', true),
); );
} }
/** /**
* @dataProvider getInvalidValues * @dataProvider getInvalidValues
*/ */
public function testInvalidValues($value, $skip = false) public function testInvalidValues($value, $mbOnly = false)
{ {
if (!$skip) { if ($mbOnly && !function_exists('mb_strlen')) {
$constraint = new SizeLength(array('min' => 6, 'max' => 10)); return $this->markTestSkipped('mb_strlen does not exist');
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
$this->context->expects($this->once())
->method('addViolation');
$constraint = new SizeLength(array('min' => 6, 'max' => 10));
$this->assertFalse($this->validator->isValid($value, $constraint));
} }
public function getInvalidValues() public function getInvalidValues()
@ -88,49 +109,64 @@ class SizeLengthValidatorTest extends \PHPUnit_Framework_TestCase
array(12345678901), array(12345678901),
array('12345'), array('12345'),
array('12345678901'), array('12345678901'),
array('üüüüü', !function_exists('mb_strlen')), array('üüüüü', true),
array('üüüüüüüüüüü', !function_exists('mb_strlen')), array('üüüüüüüüüüü', true),
array('ééééé', !function_exists('mb_strlen')), array('ééééé', true),
array('ééééééééééé', !function_exists('mb_strlen')), array('ééééééééééé', true),
); );
} }
public function testMessageIsSet() public function testMinMessageIsSet()
{ {
$constraint = new SizeLength(array( $constraint = new SizeLength(array(
'min' => 5, 'min' => 5,
'max' => 10, 'max' => 10,
'minMessage' => 'myMinMessage', 'minMessage' => 'myMessage',
'maxMessage' => 'myMaxMessage',
)); ));
$this->assertFalse($this->validator->isValid('1234', $constraint)); $this->context->expects($this->once())
$this->assertEquals('myMinMessage', $this->validator->getMessageTemplate()); ->method('addViolation')
$this->assertEquals(array( ->with('myMessage', array(
'{{ value }}' => '1234', '{{ value }}' => '1234',
'{{ limit }}' => 5, '{{ limit }}' => 5,
), $this->validator->getMessageParameters()); ));
$this->assertFalse($this->validator->isValid('12345678901', $constraint)); $this->assertFalse($this->validator->isValid('1234', $constraint));
$this->assertEquals('myMaxMessage', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ value }}' => '12345678901',
'{{ limit }}' => 10,
), $this->validator->getMessageParameters());
} }
public function testExactErrorMessage() public function testMaxMessageIsSet()
{
$constraint = new SizeLength(array(
'min' => 5,
'max' => 10,
'maxMessage' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => '12345678901',
'{{ limit }}' => 10,
));
$this->assertFalse($this->validator->isValid('12345678901', $constraint));
}
public function testExactMessageIsSet()
{ {
$constraint = new SizeLength(array( $constraint = new SizeLength(array(
'min' => 5, 'min' => 5,
'max' => 5, 'max' => 5,
'exactMessage' => 'myMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => '1234',
'{{ limit }}' => 5,
));
$this->assertFalse($this->validator->isValid('1234', $constraint)); $this->assertFalse($this->validator->isValid('1234', $constraint));
$this->assertEquals('This value should have exactly {{ limit }} characters', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ value }}' => '1234',
'{{ limit }}' => 5,
), $this->validator->getMessageParameters());
} }
} }

View File

@ -16,15 +16,21 @@ use Symfony\Component\Validator\Constraints\SizeValidator;
class SizeValidatorTest extends \PHPUnit_Framework_TestCase class SizeValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new SizeValidator(); $this->validator = new SizeValidator();
$this->validator->initialize($this->context);
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Size(array('min' => 10, 'max' => 20)))); $this->assertTrue($this->validator->isValid(null, new Size(array('min' => 10, 'max' => 20))));
} }
@ -33,6 +39,9 @@ class SizeValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($value) public function testValidValues($value)
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Size(array('min' => 10, 'max' => 20)); $constraint = new Size(array('min' => 10, 'max' => 20));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
} }
@ -56,6 +65,9 @@ class SizeValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidValues($value) public function testInvalidValues($value)
{ {
$this->context->expects($this->once())
->method('addViolation');
$constraint = new Size(array('min' => 10, 'max' => 20)); $constraint = new Size(array('min' => 10, 'max' => 20));
$this->assertFalse($this->validator->isValid($value, $constraint)); $this->assertFalse($this->validator->isValid($value, $constraint));
} }
@ -71,27 +83,39 @@ class SizeValidatorTest extends \PHPUnit_Framework_TestCase
); );
} }
public function testMessageIsSet() public function testMinMessageIsSet()
{ {
$constraint = new Size(array( $constraint = new Size(array(
'min' => 10, 'min' => 10,
'max' => 20, 'max' => 20,
'minMessage' => 'myMinMessage', 'minMessage' => 'myMessage',
'maxMessage' => 'myMaxMessage',
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => 9,
'{{ limit }}' => 10,
));
$this->assertFalse($this->validator->isValid(9, $constraint)); $this->assertFalse($this->validator->isValid(9, $constraint));
$this->assertEquals('myMinMessage', $this->validator->getMessageTemplate()); }
$this->assertEquals(array(
'{{ value }}' => 9, public function testMaxMessageIsSet()
'{{ limit }}' => 10, {
), $this->validator->getMessageParameters()); $constraint = new Size(array(
'min' => 10,
'max' => 20,
'maxMessage' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => 21,
'{{ limit }}' => 20,
));
$this->assertFalse($this->validator->isValid(21, $constraint)); $this->assertFalse($this->validator->isValid(21, $constraint));
$this->assertEquals('myMaxMessage', $this->validator->getMessageTemplate());
$this->assertEquals(array(
'{{ value }}' => 21,
'{{ limit }}' => 20,
), $this->validator->getMessageParameters());
} }
} }

View File

@ -16,37 +16,51 @@ use Symfony\Component\Validator\Constraints\TimeValidator;
class TimeValidatorTest extends \PHPUnit_Framework_TestCase class TimeValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new TimeValidator(); $this->validator = new TimeValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Time())); $this->assertTrue($this->validator->isValid(null, new Time()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Time())); $this->assertTrue($this->validator->isValid('', new Time()));
} }
public function testDateTimeClassIsValid() public function testDateTimeClassIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(new \DateTime(), new Time())); $this->assertTrue($this->validator->isValid(new \DateTime(), new Time()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Time()); $this->validator->isValid(new \stdClass(), new Time());
} }
@ -55,6 +69,9 @@ class TimeValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidTimes($time) public function testValidTimes($time)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($time, new Time())); $this->assertTrue($this->validator->isValid($time, new Time()));
} }
@ -72,7 +89,17 @@ class TimeValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidTimes($time) public function testInvalidTimes($time)
{ {
$this->assertFalse($this->validator->isValid($time, new Time())); $constraint = new Time(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $time,
));
$this->assertFalse($this->validator->isValid($time, $constraint));
} }
public function getInvalidTimes() public function getInvalidTimes()
@ -87,17 +114,4 @@ class TimeValidatorTest extends \PHPUnit_Framework_TestCase
array('00:00:60'), array('00:00:60'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Time(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -16,25 +16,35 @@ use Symfony\Component\Validator\Constraints\TrueValidator;
class TrueValidatorTest extends \PHPUnit_Framework_TestCase class TrueValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new TrueValidator(); $this->validator = new TrueValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new True())); $this->assertTrue($this->validator->isValid(null, new True()));
} }
public function testTrueIsValid() public function testTrueIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(true, new True())); $this->assertTrue($this->validator->isValid(true, new True()));
} }
@ -44,8 +54,11 @@ class TrueValidatorTest extends \PHPUnit_Framework_TestCase
'message' => 'myMessage' 'message' => 'myMessage'
)); ));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
));
$this->assertFalse($this->validator->isValid(false, $constraint)); $this->assertFalse($this->validator->isValid(false, $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array());
} }
} }

View File

@ -19,25 +19,35 @@ class TypeValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected static $file; protected static $file;
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new TypeValidator(); $this->validator = new TypeValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Type(array('type' => 'integer')))); $this->assertTrue($this->validator->isValid(null, new Type(array('type' => 'integer'))));
} }
public function testEmptyIsValidIfString() public function testEmptyIsValidIfString()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Type(array('type' => 'string')))); $this->assertTrue($this->validator->isValid('', new Type(array('type' => 'string'))));
} }
@ -51,6 +61,9 @@ class TypeValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidValues($value, $type) public function testValidValues($value, $type)
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Type(array('type' => $type)); $constraint = new Type(array('type' => $type));
$this->assertTrue($this->validator->isValid($value, $constraint)); $this->assertTrue($this->validator->isValid($value, $constraint));
@ -96,81 +109,60 @@ class TypeValidatorTest extends \PHPUnit_Framework_TestCase
/** /**
* @dataProvider getInvalidValues * @dataProvider getInvalidValues
*/ */
public function testInvalidValues($value, $type) public function testInvalidValues($value, $type, $valueAsString)
{ {
$constraint = new Type(array('type' => $type)); $constraint = new Type(array(
'type' => $type,
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $valueAsString,
'{{ type }}' => $type,
));
$this->assertFalse($this->validator->isValid($value, $constraint)); $this->assertFalse($this->validator->isValid($value, $constraint));
} }
public function testConstraintViolationCanHandleArrayValue()
{
$constraint = new Type(array('type' => 'string'));
$this->validator->isValid(array(0 => "Test"), $constraint);
$violation = new ConstraintViolation(
'{{ value }}',
$this->validator->getMessageParameters(),
'',
'',
''
);
$this->assertEquals('Array', $violation->getMessage());
}
public function getInvalidValues() public function getInvalidValues()
{ {
$object = new \stdClass(); $object = new \stdClass();
$file = $this->createFile(); $file = $this->createFile();
return array( return array(
array('foobar', 'numeric'), array('foobar', 'numeric', 'foobar'),
array('foobar', 'boolean'), array('foobar', 'boolean', 'foobar'),
array('0', 'integer'), array('0', 'integer', '0'),
array('1.5', 'float'), array('1.5', 'float', '1.5'),
array(12345, 'string'), array(12345, 'string', '12345'),
array($object, 'boolean'), array($object, 'boolean', 'stdClass'),
array($object, 'numeric'), array($object, 'numeric', 'stdClass'),
array($object, 'integer'), array($object, 'integer', 'stdClass'),
array($object, 'float'), array($object, 'float', 'stdClass'),
array($object, 'string'), array($object, 'string', 'stdClass'),
array($object, 'resource'), array($object, 'resource', 'stdClass'),
array($file, 'boolean'), array($file, 'boolean', (string) $file),
array($file, 'numeric'), array($file, 'numeric', (string) $file),
array($file, 'integer'), array($file, 'integer', (string) $file),
array($file, 'float'), array($file, 'float', (string) $file),
array($file, 'string'), array($file, 'string', (string) $file),
array($file, 'object'), array($file, 'object', (string) $file),
array('12a34', 'digit'), array('12a34', 'digit', '12a34'),
array('1a#23', 'alnum'), array('1a#23', 'alnum', '1a#23'),
array('abcd1', 'alpha'), array('abcd1', 'alpha', 'abcd1'),
array("\nabc", 'cntrl'), array("\nabc", 'cntrl', "\nabc"),
array("abc\n", 'graph'), array("abc\n", 'graph', "abc\n"),
array('abCDE', 'lower'), array('abCDE', 'lower', 'abCDE'),
array('ABcde', 'upper'), array('ABcde', 'upper', 'ABcde'),
array("\nabc", 'print'), array("\nabc", 'print', "\nabc"),
array('abc&$!', 'punct'), array('abc&$!', 'punct', 'abc&$!'),
array("\nabc", 'space'), array("\nabc", 'space', "\nabc"),
array('AR1012', 'xdigit'), array('AR1012', 'xdigit', 'AR1012'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Type(array(
'type' => 'numeric',
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
'{{ type }}' => 'numeric',
));
}
protected function createFile() protected function createFile()
{ {
if (!self::$file) { if (!self::$file) {

View File

@ -16,32 +16,43 @@ use Symfony\Component\Validator\Constraints\UrlValidator;
class UrlValidatorTest extends \PHPUnit_Framework_TestCase class UrlValidatorTest extends \PHPUnit_Framework_TestCase
{ {
protected $context;
protected $validator; protected $validator;
protected function setUp() protected function setUp()
{ {
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new UrlValidator(); $this->validator = new UrlValidator();
$this->validator->initialize($this->context);
} }
protected function tearDown() protected function tearDown()
{ {
$this->context = null;
$this->validator = null; $this->validator = null;
} }
public function testNullIsValid() public function testNullIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid(null, new Url())); $this->assertTrue($this->validator->isValid(null, new Url()));
} }
public function testEmptyStringIsValid() public function testEmptyStringIsValid()
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid('', new Url())); $this->assertTrue($this->validator->isValid('', new Url()));
} }
/**
* @expectedException Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType() public function testExpectsStringCompatibleType()
{ {
$this->setExpectedException('Symfony\Component\Validator\Exception\UnexpectedTypeException');
$this->validator->isValid(new \stdClass(), new Url()); $this->validator->isValid(new \stdClass(), new Url());
} }
@ -50,6 +61,9 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testValidUrls($url) public function testValidUrls($url)
{ {
$this->context->expects($this->never())
->method('addViolation');
$this->assertTrue($this->validator->isValid($url, new Url())); $this->assertTrue($this->validator->isValid($url, new Url()));
} }
@ -92,7 +106,17 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testInvalidUrls($url) public function testInvalidUrls($url)
{ {
$this->assertFalse($this->validator->isValid($url, new Url())); $constraint = new Url(array(
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', array(
'{{ value }}' => $url,
));
$this->assertFalse($this->validator->isValid($url, $constraint));
} }
public function getInvalidUrls() public function getInvalidUrls()
@ -118,6 +142,9 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
*/ */
public function testCustomProtocolIsValid($url) public function testCustomProtocolIsValid($url)
{ {
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Url(array( $constraint = new Url(array(
'protocols' => array('ftp', 'file', 'git') 'protocols' => array('ftp', 'file', 'git')
)); ));
@ -133,17 +160,4 @@ class UrlValidatorTest extends \PHPUnit_Framework_TestCase
array('git://[::1]/'), array('git://[::1]/'),
); );
} }
public function testMessageIsSet()
{
$constraint = new Url(array(
'message' => 'myMessage'
));
$this->assertFalse($this->validator->isValid('foobar', $constraint));
$this->assertEquals($this->validator->getMessageTemplate(), 'myMessage');
$this->assertEquals($this->validator->getMessageParameters(), array(
'{{ value }}' => 'foobar',
));
}
} }

View File

@ -11,151 +11,213 @@
namespace Symfony\Tests\Component\Validator; namespace Symfony\Tests\Component\Validator;
use Symfony\Component\Validator\GlobalExecutionContext;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
class ExecutionContextTest extends \PHPUnit_Framework_TestCase class ExecutionContextTest extends \PHPUnit_Framework_TestCase
{ {
protected $walker; protected $walker;
protected $metadataFactory; protected $metadataFactory;
protected $globalContext;
protected $context; protected $context;
protected function setUp() protected function setUp()
{ {
$this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false); $this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false);
$this->metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface'); $this->metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$this->context = new ExecutionContext('Root', $this->walker, $this->metadataFactory); $this->globalContext = new GlobalExecutionContext('Root', $this->walker, $this->metadataFactory);
$this->context = new ExecutionContext($this->globalContext, 'currentValue', 'foo.bar', 'Group', 'ClassName', 'propertyName');
} }
protected function tearDown() protected function tearDown()
{ {
$this->walker = null; $this->globalContext = null;
$this->metadataFactory = null;
$this->context = null; $this->context = null;
} }
public function testInit()
{
$this->assertCount(0, $this->context->getViolations());
$this->assertSame('Root', $this->context->getRoot());
$this->assertSame('foo.bar', $this->context->getPropertyPath());
$this->assertSame('ClassName', $this->context->getCurrentClass());
$this->assertSame('propertyName', $this->context->getCurrentProperty());
$this->assertSame('Group', $this->context->getGroup());
$this->assertSame($this->walker, $this->context->getGraphWalker());
$this->assertSame($this->metadataFactory, $this->context->getMetadataFactory());
}
public function testClone() public function testClone()
{ {
$clone = clone $this->context; $clone = clone $this->context;
$this->assertNotSame($this->context, $clone); $this->assertNotSame($this->context->getViolations(), $clone->getViolations());
} }
public function testAddViolation() public function testAddViolation()
{ {
$this->assertCount(0, $this->context->getViolations()); $this->context->addViolation('Error', array('foo' => 'bar'), 'invalid');
$this->context->addViolation('', array(), '');
$this->assertCount(1, $this->context->getViolations()); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Error',
array('foo' => 'bar'),
'Root',
'foo.bar',
'invalid'
),
)), $this->context->getViolations());
} }
public function testGetViolations() public function testAddViolationUsesPreconfiguredValueIfNotPassed()
{ {
$this->context->addViolation('', array(), ''); $this->context->addViolation('Error');
$violations = $this->context->getViolations(); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
$this->assertCount(1, $violations); 'Error',
$this->assertInstanceOf('Symfony\Component\Validator\ConstraintViolationList', $violations); array(),
'Root',
$this->assertInstanceOf('ArrayIterator', $violations->getIterator()); 'foo.bar',
'currentValue'
$this->assertTrue(isset($violations[0])); ),
$this->assertFalse(isset($violations[1])); )), $this->context->getViolations());
$violations[] = 'fake';
$this->assertEquals('fake', $violations[1]);
$this->assertTrue(isset($violations[1]));
unset($violations[1]);
$this->assertFalse(isset($violations[1]));
$violations[0] = 'fake';
$this->assertEquals('fake', $violations[0]);
} }
public function testViolationsMerge() public function testAddViolationUsesPassedNullValue()
{ {
$this->context->addViolation('Message 1', array(), ''); // passed null value should override preconfigured value "invalid"
$this->context->addViolation('Message 2', array(), ''); $this->context->addViolation('Error', array('foo' => 'bar'), null);
$violations1 = $this->context->getViolations(); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
$this->context->addViolation('', array(), ''); 'Error',
array('foo' => 'bar'),
$violations2 = $this->context->getViolations(); 'Root',
unset($violations2[1]); 'foo.bar',
null
$violations1->addAll($violations2); ),
)), $this->context->getViolations());
$this->assertEmpty($violations1[2]->getMessage());
} }
public function testViolationsAsString() public function testAddViolationAtPath()
{ {
$this->context->addViolation('Message 1', array(), ''); // override preconfigured property path
$this->context->addViolation('Message 2', array(), ''); $this->context->addViolationAtPath('bar.baz', 'Error', array('foo' => 'bar'), 'invalid');
$violations = $this->context->getViolations(); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
$expected = <<<EOF 'Error',
Root.: array('foo' => 'bar'),
Message 1 'Root',
Root.: 'bar.baz',
Message 2 'invalid'
),
EOF; )), $this->context->getViolations());
$this->assertEquals($expected, $violations->__toString());
} }
public function testGetRoot() public function testAddViolationAtPathUsesPreconfiguredValueIfNotPassed()
{ {
$this->assertEquals('Root', $this->context->getRoot()); $this->context->addViolationAtPath('bar.baz', 'Error');
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Error',
array(),
'Root',
'bar.baz',
'currentValue'
),
)), $this->context->getViolations());
} }
public function testSetGetPropertyPath() public function testAddViolationAtPathUsesPassedNullValue()
{ {
$this->context->setPropertyPath('property_path'); // passed null value should override preconfigured value "invalid"
$this->context->addViolationAtPath('bar.baz', 'Error', array('foo' => 'bar'), null);
$this->assertEquals('property_path', $this->context->getPropertyPath()); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Error',
array('foo' => 'bar'),
'Root',
'bar.baz',
null
),
)), $this->context->getViolations());
} }
public function testSetGetCurrentClass() public function testAddViolationAtSubPath()
{ {
$this->context->setCurrentClass('current_class'); // override preconfigured property path
$this->context->addViolationAtSubPath('bam.baz', 'Error', array('foo' => 'bar'), 'invalid');
$this->assertEquals('current_class', $this->context->getCurrentClass()); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Error',
array('foo' => 'bar'),
'Root',
'foo.bar.bam.baz',
'invalid'
),
)), $this->context->getViolations());
} }
public function testSetGetCurrentProperty() public function testAddViolationAtSubPathUsesPreconfiguredValueIfNotPassed()
{ {
$this->context->setCurrentProperty('current_property'); $this->context->addViolationAtSubPath('bam.baz', 'Error');
$this->assertEquals('current_property', $this->context->getCurrentProperty()); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Error',
array(),
'Root',
'foo.bar.bam.baz',
'currentValue'
),
)), $this->context->getViolations());
} }
public function testSetGetGroup() public function testAddViolationAtSubPathUsesPassedNullValue()
{ {
$this->context->setGroup('group'); // passed null value should override preconfigured value "invalid"
$this->context->addViolationAtSubPath('bam.baz', 'Error', array('foo' => 'bar'), null);
$this->assertEquals('group', $this->context->getGroup()); $this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Error',
array('foo' => 'bar'),
'Root',
'foo.bar.bam.baz',
null
),
)), $this->context->getViolations());
} }
public function testGetGraphWalker() public function testGetPropertyPath()
{ {
$this->assertSame($this->walker, $this->context->getGraphWalker()); $this->assertEquals('foo.bar', $this->context->getPropertyPath());
$this->assertInstanceOf(
'Symfony\Component\Validator\GraphWalker',
$this->context->getGraphWalker()
);
} }
public function testGetMetadataFactory() public function testGetPropertyPathWithIndexPath()
{ {
$this->assertSame($this->metadataFactory, $this->context->getMetadataFactory()); $this->assertEquals('foo.bar[bam]', $this->context->getPropertyPath('[bam]'));
$this->assertInstanceOf( }
'Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface',
$this->context->getMetadataFactory() public function testGetPropertyPathWithEmptyPath()
); {
$this->assertEquals('foo.bar', $this->context->getPropertyPath(''));
}
public function testGetPropertyPathWithEmptyCurrentPropertyPath()
{
$this->context = new ExecutionContext($this->globalContext, 'currentValue', '', 'Group', 'ClassName', 'propertyName');
$this->assertEquals('bam.baz', $this->context->getPropertyPath('bam.baz'));
} }
} }

View File

@ -4,13 +4,23 @@ namespace Symfony\Tests\Component\Validator\Fixtures;
use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\ExecutionContext;
class ConstraintAValidator extends ConstraintValidator class ConstraintAValidator extends ConstraintValidator
{ {
static public $passedContext;
public function initialize(ExecutionContext $context)
{
parent::initialize($context);
self::$passedContext = $context;
}
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
if ('VALID' != $value) { if ('VALID' != $value) {
$this->setMessage('message', array('param' => 'value')); $this->context->addViolation('message', array('param' => 'value'));
return false; return false;
} }

View File

@ -6,7 +6,7 @@ use Symfony\Component\Validator\Constraint;
class FailingConstraint extends Constraint class FailingConstraint extends Constraint
{ {
public $message = ''; public $message = 'Failed';
public function getTargets() public function getTargets()
{ {

View File

@ -9,7 +9,7 @@ class FailingConstraintValidator extends ConstraintValidator
{ {
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
$this->setMessage($constraint->message, array()); $this->context->addViolation($constraint->message, array());
return false; return false;
} }

View File

@ -0,0 +1,63 @@
<?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\Tests\Component\Validator;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\GlobalExecutionContext;
class GlobalExecutionContextTest extends \PHPUnit_Framework_TestCase
{
protected $walker;
protected $metadataFactory;
protected $context;
protected function setUp()
{
$this->walker = $this->getMock('Symfony\Component\Validator\GraphWalker', array(), array(), '', false);
$this->metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$this->context = new GlobalExecutionContext('Root', $this->walker, $this->metadataFactory);
}
protected function tearDown()
{
$this->walker = null;
$this->metadataFactory = null;
$this->context = null;
}
public function testInit()
{
$this->assertCount(0, $this->context->getViolations());
$this->assertSame('Root', $this->context->getRoot());
$this->assertSame($this->walker, $this->context->getGraphWalker());
$this->assertSame($this->metadataFactory, $this->context->getMetadataFactory());
}
public function testClone()
{
$clone = clone $this->context;
$this->assertNotSame($this->context->getViolations(), $clone->getViolations());
}
public function testAddViolation()
{
$violation = new ConstraintViolation('Error', array(), 'Root', 'foo.bar', 'invalid');
$this->context->addViolation($violation);
$this->assertEquals(new ConstraintViolationList(array($violation)), $this->context->getViolations());
}
}

View File

@ -11,6 +11,8 @@
namespace Symfony\Tests\Component\Validator; namespace Symfony\Tests\Component\Validator;
use Symfony\Tests\Component\Validator\Fixtures\ConstraintAValidator;
require_once __DIR__.'/Fixtures/Entity.php'; require_once __DIR__.'/Fixtures/Entity.php';
require_once __DIR__.'/Fixtures/Reference.php'; require_once __DIR__.'/Fixtures/Reference.php';
require_once __DIR__.'/Fixtures/ConstraintA.php'; require_once __DIR__.'/Fixtures/ConstraintA.php';
@ -54,13 +56,17 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$this->metadata = null; $this->metadata = null;
} }
public function testWalkObjectUpdatesContext() public function testWalkObjectPassesCorrectClassAndProperty()
{ {
$this->metadata->addConstraint(new ConstraintA()); $this->metadata->addConstraint(new ConstraintA());
$this->walker->walkObject($this->metadata, new Entity(), 'Default', ''); $entity = new Entity();
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
$this->assertEquals('Symfony\Tests\Component\Validator\Fixtures\Entity', $this->getContext()->getCurrentClass()); $context = ConstraintAValidator::$passedContext;
$this->assertEquals('Symfony\Tests\Component\Validator\Fixtures\Entity', $context->getCurrentClass());
$this->assertNull($context->getCurrentProperty());
} }
public function testWalkObjectValidatesConstraints() public function testWalkObjectValidatesConstraints()
@ -143,7 +149,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
// validated // validated
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
'Root', 'Root',
'firstName', 'firstName',
@ -175,7 +181,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
// "Default" was launched // "Default" was launched
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
'Root', 'Root',
'reference', 'reference',
@ -202,7 +208,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
// Only group "Second" was validated // Only group "Second" was validated
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
'Root', 'Root',
'lastName', 'lastName',
@ -212,14 +218,16 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$this->assertEquals($violations, $this->walker->getViolations()); $this->assertEquals($violations, $this->walker->getViolations());
} }
public function testWalkPropertyUpdatesContext() public function testWalkPropertyPassesCorrectClassAndProperty()
{ {
$this->metadata->addPropertyConstraint('firstName', new ConstraintA()); $this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->walker->walkPropertyValue($this->metadata, 'firstName', 'value', 'Default', ''); $this->walker->walkPropertyValue($this->metadata, 'firstName', 'value', 'Default', '');
$this->assertEquals('Symfony\Tests\Component\Validator\Fixtures\Entity', $this->getContext()->getCurrentClass()); $context = ConstraintAValidator::$passedContext;
$this->assertEquals('firstName', $this->getContext()->getCurrentProperty());
$this->assertEquals('Symfony\Tests\Component\Validator\Fixtures\Entity', $context->getCurrentClass());
$this->assertEquals('firstName', $context->getCurrentProperty());
} }
public function testWalkPropertyValueValidatesConstraints() public function testWalkPropertyValueValidatesConstraints()
@ -254,7 +262,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
'Root', 'Root',
'path', 'path',
@ -286,7 +294,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
'Root', 'Root',
'path[key]', 'path[key]',
@ -319,7 +327,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
'Root', 'Root',
'path[key]', 'path[key]',
@ -441,7 +449,7 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$this->walker->walkConstraint($constraint, array('foo' => 'VALID'), 'Default', 'collection'); $this->walker->walkConstraint($constraint, array('foo' => 'VALID'), 'Default', 'collection');
$violations = $this->walker->getViolations(); $violations = $this->walker->getViolations();
$this->assertEquals('collection', $violations[0]->getPropertyPath()); $this->assertEquals('collection[bar]', $violations[0]->getPropertyPath());
} }
public function testWalkObjectUsesCorrectPropertyPathInViolationsWhenUsingNestedCollections() public function testWalkObjectUsesCorrectPropertyPathInViolationsWhenUsingNestedCollections()
@ -455,12 +463,12 @@ class GraphWalkerTest extends \PHPUnit_Framework_TestCase
$this->walker->walkConstraint($constraint, array('foo' => array('foo' => 'VALID')), 'Default', 'collection'); $this->walker->walkConstraint($constraint, array('foo' => array('foo' => 'VALID')), 'Default', 'collection');
$violations = $this->walker->getViolations(); $violations = $this->walker->getViolations();
$this->assertEquals('collection[foo]', $violations[0]->getPropertyPath()); $this->assertEquals('collection[foo][bar]', $violations[0]->getPropertyPath());
} }
protected function getContext() protected function getProperty($property)
{ {
$p = new \ReflectionProperty($this->walker, 'context'); $p = new \ReflectionProperty($this->walker, $property);
$p->setAccessible(true); $p->setAccessible(true);
return $p->getValue($this->walker); return $p->getValue($this->walker);

View File

@ -55,7 +55,7 @@ class ValidatorTest extends \PHPUnit_Framework_TestCase
// Only the constraint of group "Default" failed // Only the constraint of group "Default" failed
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
$entity, $entity,
'firstName', 'firstName',
@ -78,7 +78,7 @@ class ValidatorTest extends \PHPUnit_Framework_TestCase
// Only the constraint of group "Custom" failed // Only the constraint of group "Custom" failed
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
$entity, $entity,
'lastName', 'lastName',
@ -103,14 +103,14 @@ class ValidatorTest extends \PHPUnit_Framework_TestCase
// The constraints of both groups failed // The constraints of both groups failed
$violations = new ConstraintViolationList(); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
$entity, $entity,
'firstName', 'firstName',
'' ''
)); ));
$violations->add(new ConstraintViolation( $violations->add(new ConstraintViolation(
'', 'Failed',
array(), array(),
$entity, $entity,
'lastName', 'lastName',
@ -148,9 +148,16 @@ class ValidatorTest extends \PHPUnit_Framework_TestCase
public function testValidateValue() public function testValidateValue()
{ {
$result = $this->validator->validateValue('Bernhard', new FailingConstraint()); $violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
array(),
'',
'',
'Bernhard'
));
$this->assertCount(1, $result); $this->assertEquals($violations, $this->validator->validateValue('Bernhard', new FailingConstraint()));
} }
public function testGetMetadataFactory() public function testGetMetadataFactory()