[Validator] removed deprecated methods

This commit is contained in:
Fabien Potencier 2013-03-01 09:39:10 +01:00
parent 65e3b1684b
commit e0385a2c1c
25 changed files with 8 additions and 2671 deletions

View File

@ -11,8 +11,6 @@
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Exception\ValidatorException;
/**
* Base class for constraint validators
*
@ -27,93 +25,11 @@ abstract class ConstraintValidator implements ConstraintValidatorInterface
*/
protected $context;
/**
* @var string
*
* @deprecated
*/
private $messageTemplate;
/**
* @var array
*
* @deprecated
*/
private $messageParameters;
/**
* {@inheritDoc}
*/
public function initialize(ExecutionContextInterface $context)
{
$this->context = $context;
$this->messageTemplate = '';
$this->messageParameters = array();
}
/**
* {@inheritDoc}
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
public function getMessageTemplate()
{
trigger_error('getMessageTemplate() is deprecated since version 2.1 and will be removed in 2.3.', E_USER_DEPRECATED);
return $this->messageTemplate;
}
/**
* {@inheritDoc}
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
public function getMessageParameters()
{
trigger_error('getMessageParameters() is deprecated since version 2.1 and will be removed in 2.3.', E_USER_DEPRECATED);
return $this->messageParameters;
}
/**
* Wrapper for $this->context->addViolation()
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
protected function setMessage($template, array $parameters = array())
{
trigger_error('setMessage() is deprecated since version 2.1 and will be removed in 2.3.', E_USER_DEPRECATED);
$this->messageTemplate = $template;
$this->messageParameters = $parameters;
if (!$this->context instanceof ExecutionContext) {
throw new ValidatorException('ConstraintValidator::initialize() must be called before setting violation messages');
}
$this->context->addViolation($template, $parameters);
}
/**
* Stub implementation delegating to the deprecated isValid method.
*
* This stub exists for BC and will be dropped in Symfony 2.3.
*
* @see ConstraintValidatorInterface::validate
*/
public function validate($value, Constraint $constraint)
{
trigger_error('isValid() is deprecated since version 2.1 and will be removed in 2.3. Implement validate() instead.', E_USER_DEPRECATED);
return $this->isValid($value, $constraint);
}
/**
* BC variant of validate.
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
protected function isValid($value, Constraint $constraint)
{
}
}

View File

@ -112,64 +112,6 @@ class ExecutionContext implements ExecutionContextInterface
));
}
/**
* 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.
* @param integer|null $pluralization The number to use to pluralize of the message.
* @param integer|null $code The violation code.
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function addViolationAtPath($propertyPath, $message, array $params = array(), $invalidValue = null, $pluralization = null, $code = null)
{
trigger_error('addViolationAtPath() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
$this->globalContext->getViolations()->add(new ConstraintViolation(
null === $pluralization
? $this->translator->trans($message, $params, $this->translationDomain)
: $this->translator->transChoice($message, $pluralization, $params, $this->translationDomain),
$message,
$params,
$this->globalContext->getRoot(),
$propertyPath,
// check using func_num_args() to allow passing null values
func_num_args() >= 4 ? $invalidValue : $this->value,
$pluralization,
$code
));
}
/**
* 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.
* @param integer|null $pluralization The number to use to pluralize of the message.
* @param integer|null $code The violation code.
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use the
* method {@link addViolationAt} instead.
*/
public function addViolationAtSubPath($subPath, $message, array $params = array(), $invalidValue = null, $pluralization = null, $code = null)
{
trigger_error('addViolationAtSubPath() is deprecated since version 2.2 and will be removed in 2.3. Use addViolationAt() instead.', E_USER_DEPRECATED);
if (func_num_args() >= 4) {
$this->addViolationAt($subPath, $message, $params, $invalidValue, $pluralization, $code);
} else {
// Needed in order to make the check for func_num_args() inside work
$this->addViolationAt($subPath, $message, $params);
}
}
/**
* {@inheritdoc}
*/
@ -312,74 +254,6 @@ class ExecutionContext implements ExecutionContextInterface
}
}
/**
* Returns the class name of the current node.
*
* @return string|null The class name or null, if the current node does not
* hold information about a class.
*
* @see getClassName
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use
* {@link getClassName} instead.
*/
public function getCurrentClass()
{
trigger_error('getCurrentClass() is deprecated since version 2.2 and will be removed in 2.3. Use getClassName() instead', E_USER_DEPRECATED);
return $this->getClassName();
}
/**
* Returns the property name of the current node.
*
* @return string|null The property name or null, if the current node does
* not hold information about a property.
*
* @see getPropertyName
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use
* {@link getClassName} instead.
*/
public function getCurrentProperty()
{
trigger_error('getCurrentProperty() is deprecated since version 2.2 and will be removed in 2.3. Use getClassName() instead', E_USER_DEPRECATED);
return $this->getPropertyName();
}
/**
* Returns the currently validated value.
*
* @return mixed The current value.
*
* @see getValue
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use
* {@link getValue} instead.
*/
public function getCurrentValue()
{
trigger_error('getCurrentValue() is deprecated since version 2.2 and will be removed in 2.3. Use getValue() instead', E_USER_DEPRECATED);
return $this->value;
}
/**
* Returns the graph walker instance.
*
* @return GraphWalker The graph walker.
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use
* {@link validate} and {@link validateValue} instead.
*/
public function getGraphWalker()
{
trigger_error('getGraphWalker() is deprecated since version 2.2 and will be removed in 2.3. Use validate() and validateValue() instead', E_USER_DEPRECATED);
return $this->globalContext->getVisitor()->getGraphWalker();
}
/**
* {@inheritdoc}
*/

View File

@ -1,236 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Translation\TranslatorInterface;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\MemberMetadata;
/**
* Responsible for walking over and initializing validation on different
* types of items.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. This class
* has been replaced by {@link ValidationVisitorInterface} and
* {@link MetadataInterface}.
*/
class GraphWalker
{
/**
* @var ValidationVisitor
*/
private $visitor;
/**
* @var MetadataFactoryInterface
*/
private $metadataFactory;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var null|string
*/
private $translationDomain;
/**
* @var array
*/
private $validatedObjects;
/**
* Creates a new graph walker.
*
* @param ValidationVisitor $visitor
* @param MetadataFactoryInterface $metadataFactory
* @param TranslatorInterface $translator
* @param null|string $translationDomain
* @param array $validatedObjects
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function __construct(ValidationVisitor $visitor, MetadataFactoryInterface $metadataFactory, TranslatorInterface $translator, $translationDomain = null, array &$validatedObjects = array())
{
trigger_error('GraphWalker is deprecated since version 2.2 and will be removed in 2.3. This class has been replaced by ValidationVisitorInterface and MetadataInterface.', E_USER_DEPRECATED);
$this->visitor = $visitor;
$this->metadataFactory = $metadataFactory;
$this->translator = $translator;
$this->translationDomain = $translationDomain;
$this->validatedObjects = &$validatedObjects;
}
/**
* @return ConstraintViolationList
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function getViolations()
{
trigger_error('getViolations() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
return $this->visitor->getViolations();
}
/**
* Initialize validation on the given object using the given metadata
* instance and validation group.
*
* @param ClassMetadata $metadata
* @param object $object The object to validate
* @param string $group The validator group to use for validation
* @param string $propertyPath
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function walkObject(ClassMetadata $metadata, $object, $group, $propertyPath)
{
trigger_error('walkObject() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
$hash = spl_object_hash($object);
// Exit, if the object is already validated for the current group
if (isset($this->validatedObjects[$hash][$group])) {
return;
}
// Remember validating this object before starting and possibly
// traversing the object graph
$this->validatedObjects[$hash][$group] = true;
$metadata->accept($this->visitor, $object, $group, $propertyPath);
}
protected function walkObjectForGroup(ClassMetadata $metadata, $object, $group, $propertyPath, $propagatedGroup = null)
{
$metadata->accept($this->visitor, $object, $group, $propertyPath, $propagatedGroup);
}
/**
* Validates a property of a class.
*
* @param Mapping\ClassMetadata $metadata
* @param $property
* @param $object
* @param $group
* @param $propertyPath
* @param null $propagatedGroup
*
* @throws Exception\UnexpectedTypeException
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function walkProperty(ClassMetadata $metadata, $property, $object, $group, $propertyPath, $propagatedGroup = null)
{
trigger_error('walkProperty() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
if (!is_object($object)) {
throw new UnexpectedTypeException($object, 'object');
}
foreach ($metadata->getMemberMetadatas($property) as $member) {
$member->accept($this->visitor, $member->getValue($object), $group, $propertyPath, $propagatedGroup);
}
}
/**
* Validates a property of a class against a potential value.
*
* @param Mapping\ClassMetadata $metadata
* @param $property
* @param $value
* @param $group
* @param $propertyPath
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function walkPropertyValue(ClassMetadata $metadata, $property, $value, $group, $propertyPath)
{
trigger_error('walkPropertyValue() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
foreach ($metadata->getMemberMetadatas($property) as $member) {
$member->accept($this->visitor, $value, $group, $propertyPath);
}
}
protected function walkMember(MemberMetadata $metadata, $value, $group, $propertyPath, $propagatedGroup = null)
{
$metadata->accept($this->visitor, $value, $group, $propertyPath, $propagatedGroup);
}
/**
* Validates an object or an array.
*
* @param $value
* @param $group
* @param $propertyPath
* @param $traverse
* @param bool $deep
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function walkReference($value, $group, $propertyPath, $traverse, $deep = false)
{
trigger_error('walkReference() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
$this->visitor->validate($value, $group, $propertyPath, $traverse, $deep);
}
/**
* Validates a value against a constraint.
*
* @param Constraint $constraint
* @param $value
* @param $group
* @param $propertyPath
* @param null $currentClass
* @param null $currentProperty
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function walkConstraint(Constraint $constraint, $value, $group, $propertyPath, $currentClass = null, $currentProperty = null)
{
trigger_error('walkConstraint() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
$metadata = null;
// BC code to make getCurrentClass() and getCurrentProperty() work when
// called from within this method
if (null !== $currentClass) {
$metadata = $this->metadataFactory->getMetadataFor($currentClass);
if (null !== $currentProperty && $metadata instanceof PropertyMetadataContainerInterface) {
$metadata = current($metadata->getPropertyMetadata($currentProperty));
}
}
$context = new ExecutionContext(
$this->visitor,
$this->translator,
$this->translationDomain,
$metadata,
$value,
$group,
$propertyPath
);
$context->validateValue($value, $constraint);
}
}

View File

@ -21,7 +21,7 @@ use Symfony\Component\Validator\Mapping\Cache\CacheInterface;
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class ClassMetadataFactory implements ClassMetadataFactoryInterface, MetadataFactoryInterface
class ClassMetadataFactory implements MetadataFactoryInterface
{
/**
* The loader for loading the class metadata
@ -109,17 +109,4 @@ class ClassMetadataFactory implements ClassMetadataFactoryInterface, MetadataFac
return false;
}
/**
* {@inheritdoc}
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use
* {@link getMetadataFor} instead.
*/
public function getClassMetadata($class)
{
trigger_error('getClassMetadata() is deprecated since version 2.2 and will be removed in 2.3. Use getMetadataFor() instead.', E_USER_DEPRECATED);
return $this->getMetadataFor($class);
}
}

View File

@ -1,63 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Mapping;
use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Exception\NoSuchMetadataException;
/**
* An adapter for exposing {@link ClassMetadataFactoryInterface} implementations
* under the new {@link MetadataFactoryInterface}.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class ClassMetadataFactoryAdapter implements MetadataFactoryInterface
{
/**
* @var ClassMetadataFactoryInterface
*/
private $innerFactory;
public function __construct(ClassMetadataFactoryInterface $innerFactory)
{
trigger_error(sprintf('ClassMetadataFactoryInterface is deprecated since version 2.1 and will be removed in 2.3. Implement MetadataFactoryInterface instead on %s.', get_class($innerFactory)), E_USER_DEPRECATED);
$this->innerFactory = $innerFactory;
}
/**
* {@inheritdoc}
*/
public function getMetadataFor($value)
{
$class = is_object($value) ? get_class($value) : $value;
$metadata = $this->innerFactory->getClassMetadata($class);
if (null === $metadata) {
throw new NoSuchMetadataException('No metadata exists for class '. $class);
}
return $metadata;
}
/**
* {@inheritdoc}
*/
public function hasMetadataFor($value)
{
$class = is_object($value) ? get_class($value) : $value;
$return = null !== $this->innerFactory->getClassMetadata($class);
return $return;
}
}

View File

@ -1,30 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Mapping;
/**
* A factory for {@link ClassMetadata} objects.
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Implement
* {@link \Symfony\Component\Validator\MetadataFactoryInterface} instead.
*/
interface ClassMetadataFactoryInterface
{
/**
* Returns metadata for a given class.
*
* @param string $class The class name.
*
* @return ClassMetadata The class metadata instance.
*/
public function getClassMetadata($class);
}

View File

@ -188,23 +188,6 @@ abstract class MemberMetadata extends ElementMetadata implements PropertyMetadat
return $this->collectionCascadedDeeply;
}
/**
* Returns the value of this property in the given object
*
* @param object $object The object
*
* @return mixed The property value
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3. Use the
* method {@link getPropertyValue} instead.
*/
public function getValue($object)
{
trigger_error('getValue() is deprecated since version 2.2 and will be removed in 2.3. Use getPropertyValue() instead.', E_USER_DEPRECATED);
return $this->getPropertyValue($object);
}
/**
* Returns the Reflection instance of the member
*

View File

@ -1,71 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ConstraintValidatorTest_Validator extends ConstraintValidator
{
private $message;
private $params;
public function __construct($message, array $params = array())
{
$this->message = $message;
$this->params = $params;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function validate($value, Constraint $constraint)
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->setMessage($this->message, $this->params);
restore_error_handler();
}
}
class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase
{
public function testSetMessage()
{
$context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$constraint = $this->getMock('Symfony\Component\Validator\Constraint', array(), array(), '', false);
$validator = new ConstraintValidatorTest_Validator('error message', array('foo' => 'bar'));
$validator->initialize($context);
$context->expects($this->once())
->method('addViolation')
->with('error message', array('foo' => 'bar'));
$validator->validate('bam', $constraint);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ValidatorException
*/
public function testSetMessageFailsIfNoContextSet()
{
$constraint = $this->getMock('Symfony\Component\Validator\Constraint', array(), array(), '', false);
$validator = new ConstraintValidatorTest_Validator('error message', array('foo' => 'bar'));
$validator->validate('bam', $constraint);
}
}

View File

@ -1,140 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\MaxLength;
use Symfony\Component\Validator\Constraints\MaxLengthValidator;
class MaxLengthValidatorTest extends \PHPUnit_Framework_TestCase
{
protected $context;
protected $validator;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MaxLengthValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
restore_error_handler();
$this->context = null;
$this->validator = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testNullIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate(null, new MaxLength(array('limit' => 5)));
}
public function testEmptyStringIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate('', new MaxLength(array('limit' => 5)));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new MaxLength(array('limit' => 5)));
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value, $mbOnly = false)
{
if ($mbOnly && !function_exists('mb_strlen')) {
$this->markTestSkipped('mb_strlen does not exist');
}
$this->context->expects($this->never())
->method('addViolation');
$constraint = new MaxLength(array('limit' => 5));
$this->validator->validate($value, $constraint);
}
public function getValidValues()
{
return array(
array(12345),
array('12345'),
array('üüüüü', true),
array('ééééé', true),
);
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value, $mbOnly = false)
{
if ($mbOnly && !function_exists('mb_strlen')) {
$this->markTestSkipped('mb_strlen does not exist');
}
$constraint = new MaxLength(array(
'limit' => 5,
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', $this->identicalTo(array(
'{{ value }}' => (string) $value,
'{{ limit }}' => 5,
)), $this->identicalTo($value), 5);
$this->validator->validate($value, $constraint);
}
public function getInvalidValues()
{
return array(
array(123456),
array('123456'),
array('üüüüüü', true),
array('éééééé', true),
);
}
public function testConstraintGetDefaultOption()
{
$constraint = new MaxLength(array(
'limit' => 5,
));
$this->assertEquals('limit', $constraint->getDefaultOption());
}
}

View File

@ -1,124 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\Max;
use Symfony\Component\Validator\Constraints\MaxValidator;
class MaxValidatorTest extends \PHPUnit_Framework_TestCase
{
protected $context;
protected $validator;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MaxValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
restore_error_handler();
$this->context = null;
$this->validator = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testNullIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate(null, new Max(array('limit' => 10)));
}
public function testEmptyStringIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate('', new Max(array('limit' => 10)));
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value)
{
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Max(array('limit' => 10));
$this->validator->validate($value, $constraint);
}
public function getValidValues()
{
return array(
array(9.999999),
array(10),
array(10.0),
array('10'),
);
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value)
{
$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->validator->validate($value, $constraint);
}
public function getInvalidValues()
{
return array(
array(10.00001),
array('10.00001'),
array(new \stdClass()),
);
}
public function testConstraintGetDefaultOption()
{
$constraint = new Max(array(
'limit' => 10,
));
$this->assertEquals('limit', $constraint->getDefaultOption());
}
}

View File

@ -1,140 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MinLengthValidator;
class MinLengthValidatorTest extends \PHPUnit_Framework_TestCase
{
protected $context;
protected $validator;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MinLengthValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
restore_error_handler();
$this->context = null;
$this->validator = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testNullIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate(null, new MinLength(array('limit' => 6)));
}
public function testEmptyStringIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate('', new MinLength(array('limit' => 6)));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new MinLength(array('limit' => 5)));
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value, $mbOnly = false)
{
if ($mbOnly && !function_exists('mb_strlen')) {
$this->markTestSkipped('mb_strlen does not exist');
}
$this->context->expects($this->never())
->method('addViolation');
$constraint = new MinLength(array('limit' => 6));
$this->validator->validate($value, $constraint);
}
public function getValidValues()
{
return array(
array(123456),
array('123456'),
array('üüüüüü', true),
array('éééééé', true),
);
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value, $mbOnly = false)
{
if ($mbOnly && !function_exists('mb_strlen')) {
$this->markTestSkipped('mb_strlen does not exist');
}
$constraint = new MinLength(array(
'limit' => 5,
'message' => 'myMessage'
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage', $this->identicalTo(array(
'{{ value }}' => (string) $value,
'{{ limit }}' => 5,
)), $this->identicalTo($value), 5);
$this->validator->validate($value, $constraint);
}
public function getInvalidValues()
{
return array(
array(1234),
array('1234'),
array('üüüü', true),
array('éééé', true),
);
}
public function testConstraintGetDefaultOption()
{
$constraint = new MinLength(array(
'limit' => 5,
));
$this->assertEquals('limit', $constraint->getDefaultOption());
}
}

View File

@ -1,121 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests\Constraints;
use Symfony\Component\Validator\Constraints\Min;
use Symfony\Component\Validator\Constraints\MinValidator;
class MinValidatorTest extends \PHPUnit_Framework_TestCase
{
protected $context;
protected $validator;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context = $this->getMock('Symfony\Component\Validator\ExecutionContext', array(), array(), '', false);
$this->validator = new MinValidator();
$this->validator->initialize($this->context);
}
protected function tearDown()
{
restore_error_handler();
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testNullIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate(null, new Min(array('limit' => 10)));
}
public function testEmptyStringIsValid()
{
$this->context->expects($this->never())
->method('addViolation');
$this->validator->validate('', new Min(array('limit' => 10)));
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value)
{
$this->context->expects($this->never())
->method('addViolation');
$constraint = new Min(array('limit' => 10));
$this->validator->validate($value, $constraint);
}
public function getValidValues()
{
return array(
array(10.00001),
array('10.00001'),
array(10),
array(10.0),
);
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value)
{
$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->validator->validate($value, $constraint);
}
public function getInvalidValues()
{
return array(
array(9.999999),
array('9.999999'),
array(new \stdClass()),
);
}
public function testConstraintGetDefaultOption()
{
$constraint = new Min(array(
'limit' => 10,
));
$this->assertEquals('limit', $constraint->getDefaultOption());
}
}

View File

@ -11,8 +11,6 @@
namespace Symfony\Component\Validator\Tests;
use Symfony\Component\Validator\Mapping\PropertyMetadata;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ExecutionContext;
@ -64,57 +62,12 @@ class ExecutionContextTest extends \PHPUnit_Framework_TestCase
$this->context = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testInit()
{
$this->assertCount(0, $this->context->getViolations());
$this->assertSame('Root', $this->context->getRoot());
$this->assertSame('foo.bar', $this->context->getPropertyPath());
$this->assertSame('Group', $this->context->getGroup());
$this->visitor->expects($this->once())
->method('getGraphWalker')
->will($this->returnValue('GRAPHWALKER'));
// BC
set_error_handler(array($this, "deprecationErrorHandler"));
$this->assertNull($this->context->getCurrentClass());
$this->assertNull($this->context->getCurrentProperty());
$this->assertSame('GRAPHWALKER', $this->context->getGraphWalker());
$this->assertSame($this->metadataFactory, $this->context->getMetadataFactory());
restore_error_handler();
}
public function testInitWithClassMetadata()
{
// BC
set_error_handler(array($this, "deprecationErrorHandler"));
$this->metadata = new ClassMetadata(__NAMESPACE__ . '\ExecutionContextTest_TestClass');
$this->context = new ExecutionContext($this->globalContext, $this->translator, self::TRANS_DOMAIN, $this->metadata, 'currentValue', 'Group', 'foo.bar');
$this->assertSame(__NAMESPACE__ . '\ExecutionContextTest_TestClass', $this->context->getCurrentClass());
$this->assertNull($this->context->getCurrentProperty());
restore_error_handler();
}
public function testInitWithPropertyMetadata()
{
// BC
set_error_handler(array($this, "deprecationErrorHandler"));
$this->metadata = new PropertyMetadata(__NAMESPACE__ . '\ExecutionContextTest_TestClass', 'myProperty');
$this->context = new ExecutionContext($this->globalContext, $this->translator, self::TRANS_DOMAIN, $this->metadata, 'currentValue', 'Group', 'foo.bar');
$this->assertSame(__NAMESPACE__ . '\ExecutionContextTest_TestClass', $this->context->getCurrentClass());
$this->assertSame('myProperty', $this->context->getCurrentProperty());
restore_error_handler();
}
public function testClone()
@ -206,91 +159,6 @@ class ExecutionContextTest extends \PHPUnit_Framework_TestCase
)), $this->context->getViolations());
}
public function testAddViolationAtPath()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array('foo' => 'bar'))
->will($this->returnValue('Translated error'));
// override preconfigured property path
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context->addViolationAtPath('bar.baz', 'Error', array('foo' => 'bar'), 'invalid');
restore_error_handler();
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array('foo' => 'bar'),
'Root',
'bar.baz',
'invalid'
),
)), $this->context->getViolations());
}
public function testAddViolationAtPathUsesPreconfiguredValueIfNotPassed()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array())
->will($this->returnValue('Translated error'));
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context->addViolationAtPath('bar.baz', 'Error');
restore_error_handler();
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array(),
'Root',
'bar.baz',
'currentValue'
),
)), $this->context->getViolations());
}
public function testAddViolationAtPathUsesPassedNullValue()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array('foo' => 'bar'))
->will($this->returnValue('Translated error'));
$this->translator->expects($this->once())
->method('transChoice')
->with('Choice error', 3, array('foo' => 'bar'))
->will($this->returnValue('Translated choice error'));
// passed null value should override preconfigured value "invalid"
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context->addViolationAtPath('bar.baz', 'Error', array('foo' => 'bar'), null);
$this->context->addViolationAtPath('bar.baz', 'Choice error', array('foo' => 'bar'), null, 3);
restore_error_handler();
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array('foo' => 'bar'),
'Root',
'bar.baz',
null
),
new ConstraintViolation(
'Translated choice error',
'Choice error',
array('foo' => 'bar'),
'Root',
'bar.baz',
null,
3
),
)), $this->context->getViolations());
}
public function testAddViolationAt()
{
$this->translator->expects($this->once())
@ -299,9 +167,7 @@ class ExecutionContextTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue('Translated error'));
// override preconfigured property path
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context->addViolationAt('bam.baz', 'Error', array('foo' => 'bar'), 'invalid');
restore_error_handler();
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
@ -322,9 +188,7 @@ class ExecutionContextTest extends \PHPUnit_Framework_TestCase
->with('Error', array())
->will($this->returnValue('Translated error'));
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context->addViolationAt('bam.baz', 'Error');
restore_error_handler();
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
@ -350,10 +214,8 @@ class ExecutionContextTest extends \PHPUnit_Framework_TestCase
->will($this->returnValue('Translated choice error'));
// passed null value should override preconfigured value "invalid"
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context->addViolationAt('bam.baz', 'Error', array('foo' => 'bar'), null);
$this->context->addViolationAt('bam.baz', 'Choice error', array('foo' => 'bar'), null, 2);
restore_error_handler();
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(

View File

@ -1,592 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintAValidator;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\ValidationVisitor;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Fixtures\Reference;
use Symfony\Component\Validator\Tests\Fixtures\FakeMetadataFactory;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\FailingConstraint;
use Symfony\Component\Validator\GraphWalker;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Constraints\Collection;
class GraphWalkerTest extends \PHPUnit_Framework_TestCase
{
const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
/**
* @var ValidationVisitor
*/
private $visitor;
/**
* @var FakeMetadataFactory
*/
protected $metadataFactory;
/**
* @var GraphWalker
*/
protected $walker;
/**
* @var ClassMetadata
*/
protected $metadata;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->metadataFactory = new FakeMetadataFactory();
$this->visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), new DefaultTranslator());
$this->walker = $this->visitor->getGraphWalker();
$this->metadata = new ClassMetadata(self::CLASSNAME);
$this->metadataFactory->addMetadata($this->metadata);
}
protected function tearDown()
{
restore_error_handler();
$this->metadataFactory = null;
$this->visitor = null;
$this->walker = null;
$this->metadata = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testWalkObjectPassesCorrectClassAndProperty()
{
$this->metadata->addConstraint(new ConstraintA());
$entity = new Entity();
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
$context = ConstraintAValidator::$passedContext;
$this->assertEquals('Symfony\Component\Validator\Tests\Fixtures\Entity', $context->getCurrentClass());
$this->assertNull($context->getCurrentProperty());
}
public function testWalkObjectValidatesConstraints()
{
$this->metadata->addConstraint(new ConstraintA());
$this->walker->walkObject($this->metadata, new Entity(), 'Default', '');
$this->assertCount(1, $this->walker->getViolations());
}
public function testWalkObjectTwiceValidatesConstraintsOnce()
{
$this->metadata->addConstraint(new ConstraintA());
$entity = new Entity();
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
$this->assertCount(1, $this->walker->getViolations());
}
public function testWalkObjectOnceInVisitorAndOnceInWalkerValidatesConstraintsOnce()
{
$this->metadata->addConstraint(new ConstraintA());
$entity = new Entity();
$this->visitor->validate($entity, 'Default', '');
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
$this->assertCount(1, $this->walker->getViolations());
}
public function testWalkDifferentObjectsValidatesTwice()
{
$this->metadata->addConstraint(new ConstraintA());
$this->walker->walkObject($this->metadata, new Entity(), 'Default', '');
$this->walker->walkObject($this->metadata, new Entity(), 'Default', '');
$this->assertCount(2, $this->walker->getViolations());
}
public function testWalkObjectTwiceInDifferentGroupsValidatesTwice()
{
$this->metadata->addConstraint(new ConstraintA());
$this->metadata->addConstraint(new ConstraintA(array('groups' => 'Custom')));
$entity = new Entity();
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
$this->walker->walkObject($this->metadata, $entity, 'Custom', '');
$this->assertCount(2, $this->walker->getViolations());
}
public function testWalkObjectValidatesPropertyConstraints()
{
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->walker->walkObject($this->metadata, new Entity(), 'Default', '');
$this->assertCount(1, $this->walker->getViolations());
}
public function testWalkObjectValidatesGetterConstraints()
{
$this->metadata->addGetterConstraint('lastName', new ConstraintA());
$this->walker->walkObject($this->metadata, new Entity(), 'Default', '');
$this->assertCount(1, $this->walker->getViolations());
}
public function testWalkObjectInDefaultGroupTraversesGroupSequence()
{
$entity = new Entity();
$this->metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
'groups' => 'First',
)));
$this->metadata->addGetterConstraint('lastName', new FailingConstraint(array(
'groups' => 'Default',
)));
$this->metadata->setGroupSequence(array('First', $this->metadata->getDefaultGroup()));
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
// After validation of group "First" failed, no more group was
// validated
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'firstName',
''
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkObjectInGroupSequencePropagatesDefaultGroup()
{
$entity = new Entity();
$entity->reference = new Reference();
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->metadata->setGroupSequence(array($this->metadata->getDefaultGroup()));
$referenceMetadata = new ClassMetadata(get_class($entity->reference));
$referenceMetadata->addConstraint(new FailingConstraint(array(
// this constraint is only evaluated if group "Default" is
// propagated to the reference
'groups' => 'Default',
)));
$this->metadataFactory->addMetadata($referenceMetadata);
$this->walker->walkObject($this->metadata, $entity, 'Default', '');
// The validation of the reference's FailingConstraint in group
// "Default" was launched
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'reference',
$entity->reference
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkObjectInOtherGroupTraversesNoGroupSequence()
{
$entity = new Entity();
$this->metadata->addPropertyConstraint('firstName', new FailingConstraint(array(
'groups' => 'First',
)));
$this->metadata->addGetterConstraint('lastName', new FailingConstraint(array(
'groups' => $this->metadata->getDefaultGroup(),
)));
$this->metadata->setGroupSequence(array('First', $this->metadata->getDefaultGroup()));
$this->walker->walkObject($this->metadata, $entity, $this->metadata->getDefaultGroup(), '');
// Only group "Second" was validated
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'lastName',
''
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkPropertyPassesCorrectClassAndProperty()
{
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->walker->walkPropertyValue($this->metadata, 'firstName', 'value', 'Default', '');
$context = ConstraintAValidator::$passedContext;
$this->assertEquals('Symfony\Component\Validator\Tests\Fixtures\Entity', $context->getCurrentClass());
$this->assertEquals('firstName', $context->getCurrentProperty());
}
public function testWalkPropertyValueValidatesConstraints()
{
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->walker->walkPropertyValue($this->metadata, 'firstName', 'value', 'Default', '');
$this->assertCount(1, $this->walker->getViolations());
}
public function testWalkCascadedPropertyValidatesReferences()
{
$entity = new Entity();
$entityMetadata = new ClassMetadata(get_class($entity));
$this->metadataFactory->addMetadata($entityMetadata);
// add a constraint for the entity that always fails
$entityMetadata->addConstraint(new FailingConstraint());
// validate entity when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid());
// invoke validation on an object
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
$entity, // object!
'Default',
'path'
);
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'path',
$entity
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyValidatesArraysByDefault()
{
$entity = new Entity();
$entityMetadata = new ClassMetadata(get_class($entity));
$this->metadataFactory->addMetadata($entityMetadata);
// add a constraint for the entity that always fails
$entityMetadata->addConstraint(new FailingConstraint());
// validate array when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
array('key' => $entity), // array!
'Default',
'path'
);
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'path[key]',
$entity
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyValidatesTraversableByDefault()
{
$entity = new Entity();
$entityMetadata = new ClassMetadata(get_class($entity));
$this->metadataFactory->addMetadata($entityMetadata);
$this->metadataFactory->addMetadata(new ClassMetadata('ArrayIterator'));
// add a constraint for the entity that always fails
$entityMetadata->addConstraint(new FailingConstraint());
// validate array when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
new \ArrayIterator(array('key' => $entity)),
'Default',
'path'
);
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'path[key]',
$entity
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyDoesNotValidateTraversableIfDisabled()
{
$entity = new Entity();
$entityMetadata = new ClassMetadata(get_class($entity));
$this->metadataFactory->addMetadata($entityMetadata);
$this->metadataFactory->addMetadata(new ClassMetadata('ArrayIterator'));
// add a constraint for the entity that always fails
$entityMetadata->addConstraint(new FailingConstraint());
// validate array when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid(array(
'traverse' => false,
)));
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
new \ArrayIterator(array('key' => $entity)),
'Default',
'path'
);
$violations = new ConstraintViolationList();
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyDoesNotRecurseByDefault()
{
$entity = new Entity();
$entityMetadata = new ClassMetadata(get_class($entity));
$this->metadataFactory->addMetadata($entityMetadata);
$this->metadataFactory->addMetadata(new ClassMetadata('ArrayIterator'));
// add a constraint for the entity that always fails
$entityMetadata->addConstraint(new FailingConstraint());
// validate iterator when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
new \ArrayIterator(array(
// The inner iterator should not be traversed by default
'key' => new \ArrayIterator(array(
'nested' => $entity,
)),
)),
'Default',
'path'
);
$violations = new ConstraintViolationList();
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyRecursesIfDeepIsSet()
{
$entity = new Entity();
$entityMetadata = new ClassMetadata(get_class($entity));
$this->metadataFactory->addMetadata($entityMetadata);
$this->metadataFactory->addMetadata(new ClassMetadata('ArrayIterator'));
// add a constraint for the entity that always fails
$entityMetadata->addConstraint(new FailingConstraint());
// validate iterator when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid(array(
'deep' => true,
)));
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
new \ArrayIterator(array(
// The inner iterator should now be traversed
'key' => new \ArrayIterator(array(
'nested' => $entity,
)),
)),
'Default',
'path'
);
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'Failed',
'Failed',
array(),
'Root',
'path[key][nested]',
$entity
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyDoesNotValidateNestedScalarValues()
{
// validate array when validating the property "reference"
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
array('scalar', 'values'),
'Default',
'path'
);
$violations = new ConstraintViolationList();
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkCascadedPropertyDoesNotValidateNullValues()
{
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
null,
'Default',
''
);
$this->assertCount(0, $this->walker->getViolations());
}
public function testWalkCascadedPropertyRequiresObjectOrArray()
{
$this->metadata->addPropertyConstraint('reference', new Valid());
$this->setExpectedException('Symfony\Component\Validator\Exception\NoSuchMetadataException');
$this->walker->walkPropertyValue(
$this->metadata,
'reference',
'no object',
'Default',
''
);
}
public function testWalkConstraintBuildsAViolationIfFailed()
{
$constraint = new ConstraintA();
$this->walker->walkConstraint($constraint, 'foobar', 'Default', 'firstName.path');
$violations = new ConstraintViolationList();
$violations->add(new ConstraintViolation(
'message',
'message',
array('param' => 'value'),
'Root',
'firstName.path',
'foobar'
));
$this->assertEquals($violations, $this->walker->getViolations());
}
public function testWalkConstraintBuildsNoViolationIfSuccessful()
{
$constraint = new ConstraintA();
$this->walker->walkConstraint($constraint, 'VALID', 'Default', 'firstName.path');
$this->assertCount(0, $this->walker->getViolations());
}
public function testWalkObjectUsesCorrectPropertyPathInViolationsWhenUsingCollections()
{
$constraint = new Collection(array(
'foo' => new ConstraintA(),
'bar' => new ConstraintA(),
));
$this->walker->walkConstraint($constraint, array('foo' => 'VALID'), 'Default', 'collection');
$violations = $this->walker->getViolations();
$this->assertEquals('collection[bar]', $violations[0]->getPropertyPath());
}
public function testWalkObjectUsesCorrectPropertyPathInViolationsWhenUsingNestedCollections()
{
$constraint = new Collection(array(
'foo' => new Collection(array(
'foo' => new ConstraintA(),
'bar' => new ConstraintA(),
)),
));
$this->walker->walkConstraint($constraint, array('foo' => array('foo' => 'VALID')), 'Default', 'collection');
$violations = $this->walker->getViolations();
$this->assertEquals('collection[foo][bar]', $violations[0]->getPropertyPath());
}
protected function getProperty($property)
{
$p = new \ReflectionProperty($this->walker, $property);
$p->setAccessible(true);
return $p->getValue($this->walker);
}
}

View File

@ -22,21 +22,10 @@ class ClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
const PARENTCLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';
public function handle($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testLoadClassMetadata()
{
$factory = new ClassMetadataFactory(new TestLoader());
set_error_handler(array($this, 'handle'));
$metadata = $factory->getClassMetadata(self::PARENTCLASS);
restore_error_handler();
$metadata = $factory->getMetadataFor(self::PARENTCLASS);
$constraints = array(
new ConstraintA(array('groups' => array('Default', 'EntityParent'))),
@ -48,9 +37,7 @@ class ClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
public function testMergeParentConstraints()
{
$factory = new ClassMetadataFactory(new TestLoader());
set_error_handler(array($this, 'handle'));
$metadata = $factory->getClassMetadata(self::CLASSNAME);
restore_error_handler();
$metadata = $factory->getMetadataFor(self::CLASSNAME);
$constraints = array(
new ConstraintA(array('groups' => array(
@ -94,9 +81,7 @@ class ClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
$tester->assertEquals($constraints, $metadata->getConstraints());
}));
set_error_handler(array($this, 'handle'));
$metadata = $factory->getClassMetadata(self::PARENTCLASS);
restore_error_handler();
$metadata = $factory->getMetadataFor(self::PARENTCLASS);
$this->assertEquals(self::PARENTCLASS, $metadata->getClassName());
$this->assertEquals($constraints, $metadata->getConstraints());
@ -121,9 +106,7 @@ class ClassMetadataFactoryTest extends \PHPUnit_Framework_TestCase
->method('read')
->will($this->returnValue($metadata));
set_error_handler(array($this, 'handle'));
$this->assertEquals($metadata,$factory->getClassMetadata(self::PARENTCLASS));
restore_error_handler();
$this->assertEquals($metadata,$factory->getMetadataFor(self::PARENTCLASS));
}
}

View File

@ -31,15 +31,6 @@ class ValidatorBuilderTest extends \PHPUnit_Framework_TestCase
$this->builder = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testAddObjectInitializer()
{
$this->assertSame($this->builder, $this->builder->addObjectInitializer(
@ -96,15 +87,6 @@ class ValidatorBuilderTest extends \PHPUnit_Framework_TestCase
$this->assertSame($this->builder, $this->builder->disableAnnotationMapping());
}
public function testSetMetadataFactory()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->assertSame($this->builder, $this->builder->setMetadataFactory(
$this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface'))
);
restore_error_handler();
}
public function testSetMetadataCache()
{
$this->assertSame($this->builder, $this->builder->setMetadataCache(

View File

@ -1,76 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests;
use Symfony\Component\Validator\Validator;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryAdapter;
use Symfony\Component\Validator\ValidatorContext;
class ValidatorContextTest extends \PHPUnit_Framework_TestCase
{
protected $context;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->context = new ValidatorContext();
}
protected function tearDown()
{
restore_error_handler();
$this->context = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testSetClassMetadataFactory()
{
$factory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$result = $this->context->setClassMetadataFactory($factory);
$this->assertSame($this->context, $result);
$this->assertSame($factory, $this->context->getClassMetadataFactory());
}
public function testSetConstraintValidatorFactory()
{
$factory = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface');
$result = $this->context->setConstraintValidatorFactory($factory);
$this->assertSame($this->context, $result);
$this->assertSame($factory, $this->context->getConstraintValidatorFactory());
}
public function testGetValidator()
{
$metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$validatorFactory = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface');
$validator = $this->context
->setClassMetadataFactory($metadataFactory)
->setConstraintValidatorFactory($validatorFactory)
->getValidator();
$this->assertEquals(new Validator(new ClassMetadataFactoryAdapter($metadataFactory), $validatorFactory, new DefaultTranslator()), $validator);
}
}

View File

@ -1,193 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator\Tests;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryAdapter;
use Symfony\Component\Validator\Validator;
use Symfony\Component\Validator\DefaultTranslator;
use Symfony\Component\Validator\ValidatorContext;
use Symfony\Component\Validator\ValidatorFactory;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\Mapping\ClassMetadataFactory;
use Symfony\Component\Validator\Mapping\Loader\XmlFilesLoader;
use Symfony\Component\Validator\Mapping\Loader\YamlFilesLoader;
use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Component\Validator\Mapping\Loader\LoaderChain;
class ValidatorFactoryTest extends \PHPUnit_Framework_TestCase
{
protected $defaultContext;
protected $factory;
protected function setUp()
{
set_error_handler(array($this, "deprecationErrorHandler"));
$this->defaultContext = new ValidatorContext();
$this->factory = new ValidatorFactory($this->defaultContext);
}
protected function tearDown()
{
restore_error_handler();
$this->defaultContext = null;
$this->factory = null;
}
public function deprecationErrorHandler($errorNumber, $message, $file, $line, $context)
{
if ($errorNumber & E_USER_DEPRECATED) {
return true;
}
return \PHPUnit_Util_ErrorHandler::handleError($errorNumber, $message, $file, $line);
}
public function testOverrideClassMetadataFactory()
{
$factory1 = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$factory2 = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$this->defaultContext->setClassMetadataFactory($factory1);
$result = $this->factory->setClassMetadataFactory($factory2);
$this->assertSame($factory1, $this->defaultContext->getClassMetadataFactory());
$this->assertSame($factory2, $result->getClassMetadataFactory());
}
public function testOverrideConstraintValidatorFactory()
{
$factory1 = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface');
$factory2 = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface');
$this->defaultContext->setConstraintValidatorFactory($factory1);
$result = $this->factory->setConstraintValidatorFactory($factory2);
$this->assertSame($factory1, $this->defaultContext->getConstraintValidatorFactory());
$this->assertSame($factory2, $result->getConstraintValidatorFactory());
}
public function testGetValidator()
{
$metadataFactory = $this->getMock('Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface');
$validatorFactory = $this->getMock('Symfony\Component\Validator\ConstraintValidatorFactoryInterface');
$this->defaultContext
->setClassMetadataFactory($metadataFactory)
->setConstraintValidatorFactory($validatorFactory);
$validator = $this->factory->getValidator();
$this->assertEquals(new Validator(new ClassMetadataFactoryAdapter($metadataFactory), $validatorFactory, new DefaultTranslator()), $validator);
}
public function testBuildDefaultFromAnnotationsWithCustomNamespaces()
{
if (!class_exists('Doctrine\Common\Annotations\AnnotationReader')) {
$this->markTestSkipped('Annotations is required for this test');
}
$factory = ValidatorFactory::buildDefault(array(), true);
$context = new ValidatorContext();
$context
->setClassMetadataFactory(new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())))
->setConstraintValidatorFactory(new ConstraintValidatorFactory());
$this->assertEquals(new ValidatorFactory($context), $factory);
}
public function testBuildDefaultFromXml()
{
$path = __DIR__.'/Mapping/Loader/constraint-mapping.xml';
$factory = ValidatorFactory::buildDefault(array($path), false);
$context = new ValidatorContext();
$context
->setClassMetadataFactory(new ClassMetadataFactory(new XmlFilesLoader(array($path))))
->setConstraintValidatorFactory(new ConstraintValidatorFactory());
$this->assertEquals(new ValidatorFactory($context), $factory);
}
public function testBuildDefaultFromYaml()
{
$path = __DIR__.'/Mapping/Loader/constraint-mapping.yml';
$factory = ValidatorFactory::buildDefault(array($path), false);
$context = new ValidatorContext();
$context
->setClassMetadataFactory(new ClassMetadataFactory(new YamlFilesLoader(array($path))))
->setConstraintValidatorFactory(new ConstraintValidatorFactory());
$this->assertEquals(new ValidatorFactory($context), $factory);
}
public function testBuildDefaultFromStaticMethod()
{
$path = __DIR__.'/Mapping/Loader/constraint-mapping.yml';
$factory = ValidatorFactory::buildDefault(array(), false, 'loadMetadata');
$context = new ValidatorContext();
$context
->setClassMetadataFactory(new ClassMetadataFactory(new StaticMethodLoader('loadMetadata')))
->setConstraintValidatorFactory(new ConstraintValidatorFactory());
$this->assertEquals(new ValidatorFactory($context), $factory);
}
public function testBuildDefaultFromMultipleLoaders()
{
if (!class_exists('Doctrine\Common\Annotations\AnnotationReader')) {
$this->markTestSkipped('Annotations is required for this test');
}
$xmlPath = __DIR__.'/Mapping/Loader/constraint-mapping.xml';
$yamlPath = __DIR__.'/Mapping/Loader/constraint-mapping.yml';
$factory = ValidatorFactory::buildDefault(array($xmlPath, $yamlPath), true, 'loadMetadata');
$chain = new LoaderChain(array(
new XmlFilesLoader(array($xmlPath)),
new YamlFilesLoader(array($yamlPath)),
new AnnotationLoader(new AnnotationReader()),
new StaticMethodLoader('loadMetadata'),
));
$context = new ValidatorContext();
$context
->setClassMetadataFactory(new ClassMetadataFactory($chain))
->setConstraintValidatorFactory(new ConstraintValidatorFactory());
$this->assertEquals(new ValidatorFactory($context), $factory);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\MappingException
*/
public function testBuildDefaultThrowsExceptionIfNoLoaderIsFound()
{
ValidatorFactory::buildDefault();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\MappingException
*/
public function testBuildDefaultThrowsExceptionIfUnknownExtension()
{
ValidatorFactory::buildDefault(array(
__DIR__.'/Mapping/Loader/StaticMethodLoaderTest.php'
));
}
}

View File

@ -63,13 +63,6 @@ class ValidationVisitor implements ValidationVisitorInterface, GlobalExecutionCo
*/
private $validatedObjects = array();
/**
* @var GraphWalker
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
private $graphWalker;
/**
* Creates a new validation visitor.
*
@ -170,20 +163,6 @@ class ValidationVisitor implements ValidationVisitorInterface, GlobalExecutionCo
}
}
/**
* {@inheritdoc}
*/
public function getGraphWalker()
{
trigger_error('getGraphWalker() is deprecated since version 2.2 and will be removed in 2.3.', E_USER_DEPRECATED);
if (null === $this->graphWalker) {
$this->graphWalker = new GraphWalker($this, $this->metadataFactory, $this->translator, $this->translationDomain, $this->validatedObjects);
}
return $this->graphWalker;
}
/**
* {@inheritdoc}
*/

View File

@ -77,14 +77,4 @@ interface ValidationVisitorInterface
* @param string $propertyPath The current property path in the validation graph.
*/
public function visit(MetadataInterface $metadata, $value, $group, $propertyPath);
/**
* Returns a graph walker with an alternative, deprecated API of the
* visitor.
*
* @return GraphWalker The graph walker.
*
* @deprecated Deprecated since version 2.2, to be removed in 2.3.
*/
public function getGraphWalker();
}

View File

@ -12,10 +12,8 @@
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Mapping\ClassMetadataFactory;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryAdapter;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Component\Validator\Mapping\Loader\LoaderChain;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
use Symfony\Component\Validator\Mapping\Cache\CacheInterface;
use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Component\Validator\Mapping\Loader\YamlFileLoader;
@ -225,17 +223,12 @@ class ValidatorBuilder implements ValidatorBuilderInterface
/**
* {@inheritdoc}
*/
public function setMetadataFactory($metadataFactory)
public function setMetadataFactory(MetadataFactoryInterface $metadataFactory)
{
if (count($this->xmlMappings) > 0 || count($this->yamlMappings) > 0 || count($this->methodMappings) > 0 || null !== $this->annotationReader) {
throw new ValidatorException('You cannot set a custom metadata factory after adding custom mappings. You should do either of both.');
}
if ($metadataFactory instanceof ClassMetadataFactoryInterface
&& !$metadataFactory instanceof MetadataFactoryInterface) {
$metadataFactory = new ClassMetadataFactoryAdapter($metadataFactory);
}
$this->metadataFactory = $metadataFactory;
return $this;

View File

@ -113,14 +113,11 @@ interface ValidatorBuilderInterface
/**
* Sets the class metadata factory used by the validator.
*
* As of Symfony 2.3, the first parameter of this method will be typed
* against {@link MetadataFactoryInterface}.
*
* @param MetadataFactoryInterface|Mapping\ClassMetadataFactoryInterface $metadataFactory The metadata factory.
* @param MetadataFactoryInterface $metadataFactory The metadata factory.
*
* @return ValidatorBuilderInterface The builder object.
*/
public function setMetadataFactory($metadataFactory);
public function setMetadataFactory(MetadataFactoryInterface $metadataFactory);
/**
* Sets the cache for caching class metadata.

View File

@ -1,124 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryAdapter;
/**
* Default implementation of ValidatorContextInterface
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
class ValidatorContext implements ValidatorContextInterface
{
/**
* @var MetadataFactoryInterface
*/
private $metadataFactory;
/**
* The class metadata factory used in the new validator
* @var ClassMetadataFactoryInterface
*/
protected $classMetadataFactory = null;
/**
* The constraint validator factory used in the new validator
* @var ConstraintValidatorFactoryInterface
*/
protected $constraintValidatorFactory = null;
/**
* {@inheritDoc}
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function setClassMetadataFactory(ClassMetadataFactoryInterface $classMetadataFactory)
{
trigger_error('setClassMetadataFactory() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidatorBuilder() instead.', E_USER_DEPRECATED);
if ($classMetadataFactory instanceof MetadataFactoryInterface) {
$this->metadataFactory = $classMetadataFactory;
} else {
$this->metadataFactory = new ClassMetadataFactoryAdapter($classMetadataFactory);
}
$this->classMetadataFactory = $classMetadataFactory;
return $this;
}
/**
* {@inheritDoc}
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function setConstraintValidatorFactory(ConstraintValidatorFactoryInterface $constraintValidatorFactory)
{
trigger_error('setConstraintValidatorFactory() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidatorBuilder() instead.', E_USER_DEPRECATED);
$this->constraintValidatorFactory = $constraintValidatorFactory;
return $this;
}
/**
* {@inheritDoc}
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidator()} instead.
*/
public function getValidator()
{
trigger_error('getValidator() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidator() instead.', E_USER_DEPRECATED);
return new Validator(
$this->metadataFactory,
$this->constraintValidatorFactory,
new DefaultTranslator()
);
}
/**
* Returns the class metadata factory used in the new validator
*
* @return ClassMetadataFactoryInterface The factory instance
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
public function getClassMetadataFactory()
{
trigger_error('getClassMetadataFactory() is deprecated since version 2.1 and will be removed in 2.3.', E_USER_DEPRECATED);
return $this->classMetadataFactory;
}
/**
* Returns the constraint validator factory used in the new validator
*
* @return ConstraintValidatorFactoryInterface The factory instance
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
public function getConstraintValidatorFactory()
{
trigger_error('getConstraintValidatorFactory() is deprecated since version 2.1 and will be removed in 2.3.', E_USER_DEPRECATED);
return $this->constraintValidatorFactory;
}
}

View File

@ -1,65 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
/**
* Stores settings for creating a new validator and creates validators
*
* The methods in this class are chainable, i.e. they return the context
* object itself. When you have finished configuring the new validator, call
* getValidator() to create the it.
*
* <code>
* $validator = $context
* ->setClassMetadataFactory($customFactory)
* ->getValidator();
* </code>
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
interface ValidatorContextInterface
{
/**
* Sets the class metadata factory used in the new validator
*
* @param ClassMetadataFactoryInterface $classMetadataFactory The factory instance
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function setClassMetadataFactory(ClassMetadataFactoryInterface $classMetadataFactory);
/**
* Sets the constraint validator factory used in the new validator
*
* @param ConstraintValidatorFactoryInterface $constraintValidatorFactory The factory instance
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function setConstraintValidatorFactory(ConstraintValidatorFactoryInterface $constraintValidatorFactory);
/**
* Creates a new validator with the settings stored in this context
*
* @return ValidatorInterface The new validator
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidator()} instead.
*/
public function getValidator();
}

View File

@ -1,234 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Validator;
use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Validator\Exception\MappingException;
use Symfony\Component\Validator\Mapping\ClassMetadataFactory;
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
use Symfony\Component\Validator\Mapping\Loader\XmlFilesLoader;
use Symfony\Component\Validator\Mapping\Loader\YamlFilesLoader;
use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Validator\Mapping\Loader\StaticMethodLoader;
use Symfony\Component\Validator\Mapping\Loader\LoaderChain;
/**
* Creates and configures new validator objects
*
* Usually you will use the static method buildDefault() to initialize a
* factory with default configuration. To this method you can pass various
* parameters that configure where the validator mapping is found. If you
* don't pass a parameter, the mapping will be read from annotations.
*
* <code>
* // read from annotations only
* $factory = ValidatorFactory::buildDefault();
*
* // read from XML and YAML, suppress annotations
* $factory = ValidatorFactory::buildDefault(array(
* '/path/to/mapping.xml',
* '/path/to/other/mapping.yml',
* ), false);
* </code>
*
* You then have to call getValidator() to create new validators.
*
* <code>
* $validator = $factory->getValidator();
* </code>
*
* When manually constructing a factory, the default configuration of the
* validators can be passed to the constructor as a ValidatorContextInterface
* object.
*
* <code>
* $defaultContext = new ValidatorContext();
* $defaultContext->setClassMetadataFactory($metadataFactory);
* $defaultContext->setConstraintValidatorFactory($validatorFactory);
* $factory = new ValidatorFactory($defaultContext);
*
* $form = $factory->getValidator();
* </code>
*
* You can also override the default configuration by calling any of the
* methods in this class. These methods return a ValidatorContextInterface object
* on which you can override further settings or call getValidator() to create
* a form.
*
* <code>
* $form = $factory
* ->setClassMetadataFactory($customFactory);
* ->getValidator();
* </code>
*
* ValidatorFactory instances should be cached and reused in your application.
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
class ValidatorFactory implements ValidatorContextInterface
{
/**
* Holds the context with the default configuration
* @var ValidatorContextInterface
*/
protected $defaultContext;
/**
* Builds a validator factory with the default mapping loaders
*
* @param array $mappingFiles A list of XML or YAML file names
* where mapping information can be
* found. Can be empty.
* @param Boolean $annotations Whether to use annotations for
* retrieving mapping information
* @param string $staticMethod The name of the static method to
* use, if static method loading should
* be enabled
*
* @return ValidatorFactory The validator factory.
*
* @throws MappingException If any of the files in $mappingFiles
* has neither the extension ".xml" nor
* ".yml" nor ".yaml"
* @throws \RuntimeException If annotations are not supported.
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public static function buildDefault(array $mappingFiles = array(), $annotations = false, $staticMethod = null)
{
trigger_error('buildDefault() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidatorBuilder() instead.', E_USER_DEPRECATED);
$xmlMappingFiles = array();
$yamlMappingFiles = array();
$loaders = array();
$context = new ValidatorContext();
foreach ($mappingFiles as $file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if ($extension === 'xml') {
$xmlMappingFiles[] = $file;
} elseif ($extension === 'yaml' || $extension === 'yml') {
$yamlMappingFiles[] = $file;
} else {
throw new MappingException('The only supported mapping file formats are XML and YAML');
}
}
if (count($xmlMappingFiles) > 0) {
$loaders[] = new XmlFilesLoader($xmlMappingFiles);
}
if (count($yamlMappingFiles) > 0) {
$loaders[] = new YamlFilesLoader($yamlMappingFiles);
}
if ($annotations) {
if (!class_exists('Doctrine\Common\Annotations\AnnotationReader')) {
throw new \RuntimeException('Requested a ValidatorFactory with an AnnotationLoader, but the AnnotationReader was not found. You should add Doctrine Common to your project.');
}
$loaders[] = new AnnotationLoader(new AnnotationReader());
}
if ($staticMethod) {
$loaders[] = new StaticMethodLoader($staticMethod);
}
if (count($loaders) > 1) {
$loader = new LoaderChain($loaders);
} elseif (count($loaders) === 1) {
$loader = $loaders[0];
} else {
throw new MappingException('No mapping loader was found for the given parameters');
}
$context->setClassMetadataFactory(new ClassMetadataFactory($loader));
$context->setConstraintValidatorFactory(new ConstraintValidatorFactory());
return new static($context);
}
/**
* Sets the given context as default context
*
* @param ValidatorContextInterface $defaultContext A preconfigured context
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function __construct(ValidatorContextInterface $defaultContext = null)
{
trigger_error('ValidatorFactory is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidatorBuilder() instead.', E_USER_DEPRECATED);
$this->defaultContext = null === $defaultContext ? new ValidatorContext() : $defaultContext;
}
/**
* Overrides the class metadata factory of the default context and returns
* the new context
*
* @param ClassMetadataFactoryInterface $metadataFactory The new factory instance
*
* @return ValidatorContextInterface The preconfigured form context
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function setClassMetadataFactory(ClassMetadataFactoryInterface $metadataFactory)
{
trigger_error('setClassMetadataFactory() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidatorBuilder() instead.', E_USER_DEPRECATED);
$context = clone $this->defaultContext;
return $context->setClassMetadataFactory($metadataFactory);
}
/**
* Overrides the constraint validator factory of the default context and
* returns the new context
*
* @param ClassMetadataFactoryInterface $validatorFactory The new factory instance
*
* @return ValidatorContextInterface The preconfigured form context
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidatorBuilder()} instead.
*/
public function setConstraintValidatorFactory(ConstraintValidatorFactoryInterface $validatorFactory)
{
trigger_error('setConstraintValidatorFactory() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidatorBuilder() instead.', E_USER_DEPRECATED);
$context = clone $this->defaultContext;
return $context->setConstraintValidatorFactory($validatorFactory);
}
/**
* Creates a new validator with the settings stored in the default context
*
* @return ValidatorInterface The new validator
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link Validation::createValidator()} instead.
*/
public function getValidator()
{
trigger_error('getValidator() is deprecated since version 2.1 and will be removed in 2.3. Use Validation::createValidator() instead.', E_USER_DEPRECATED);
return $this->defaultContext->getValidator();
}
}