Update to drupal-org-drupal 8.0.0-rc2. For more information, see https://www.drupal.org/node/2598668

This commit is contained in:
Pantheon Automation 2015-10-21 21:44:50 -07:00 committed by Greg Anderson
parent f32e58e4b1
commit 8e18df8c36
3062 changed files with 15044 additions and 172506 deletions

View file

@ -1,209 +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\Tests\Fixtures\ClassConstraint;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintC;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintWithValue;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintWithValueAsDefault;
class ConstraintTest extends \PHPUnit_Framework_TestCase
{
public function testSetProperties()
{
$constraint = new ConstraintA(array(
'property1' => 'foo',
'property2' => 'bar',
));
$this->assertEquals('foo', $constraint->property1);
$this->assertEquals('bar', $constraint->property2);
}
public function testSetNotExistingPropertyThrowsException()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\InvalidOptionsException');
new ConstraintA(array(
'foo' => 'bar',
));
}
public function testMagicPropertiesAreNotAllowed()
{
$constraint = new ConstraintA();
$this->setExpectedException('Symfony\Component\Validator\Exception\InvalidOptionsException');
$constraint->foo = 'bar';
}
public function testInvalidAndRequiredOptionsPassed()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\InvalidOptionsException');
new ConstraintC(array(
'option1' => 'default',
'foo' => 'bar',
));
}
public function testSetDefaultProperty()
{
$constraint = new ConstraintA('foo');
$this->assertEquals('foo', $constraint->property2);
}
public function testSetDefaultPropertyDoctrineStyle()
{
$constraint = new ConstraintA(array('value' => 'foo'));
$this->assertEquals('foo', $constraint->property2);
}
public function testSetDefaultPropertyDoctrineStylePlusOtherProperty()
{
$constraint = new ConstraintA(array('value' => 'foo', 'property1' => 'bar'));
$this->assertEquals('foo', $constraint->property2);
$this->assertEquals('bar', $constraint->property1);
}
public function testSetDefaultPropertyDoctrineStyleWhenDefaultPropertyIsNamedValue()
{
$constraint = new ConstraintWithValueAsDefault(array('value' => 'foo'));
$this->assertEquals('foo', $constraint->value);
$this->assertNull($constraint->property);
}
public function testDontSetDefaultPropertyIfValuePropertyExists()
{
$constraint = new ConstraintWithValue(array('value' => 'foo'));
$this->assertEquals('foo', $constraint->value);
$this->assertNull($constraint->property);
}
public function testSetUndefinedDefaultProperty()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
new ConstraintB('foo');
}
public function testRequiredOptionsMustBeDefined()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\MissingOptionsException');
new ConstraintC();
}
public function testRequiredOptionsPassed()
{
new ConstraintC(array('option1' => 'default'));
}
public function testGroupsAreConvertedToArray()
{
$constraint = new ConstraintA(array('groups' => 'Foo'));
$this->assertEquals(array('Foo'), $constraint->groups);
}
public function testAddDefaultGroupAddsGroup()
{
$constraint = new ConstraintA(array('groups' => 'Default'));
$constraint->addImplicitGroupName('Foo');
$this->assertEquals(array('Default', 'Foo'), $constraint->groups);
}
public function testAllowsSettingZeroRequiredPropertyValue()
{
$constraint = new ConstraintA(0);
$this->assertEquals(0, $constraint->property2);
}
public function testCanCreateConstraintWithNoDefaultOptionAndEmptyArray()
{
new ConstraintB(array());
}
public function testGetTargetsCanBeString()
{
$constraint = new ClassConstraint();
$this->assertEquals('class', $constraint->getTargets());
}
public function testGetTargetsCanBeArray()
{
$constraint = new ConstraintA();
$this->assertEquals(array('property', 'class'), $constraint->getTargets());
}
public function testSerialize()
{
$constraint = new ConstraintA(array(
'property1' => 'foo',
'property2' => 'bar',
));
$restoredConstraint = unserialize(serialize($constraint));
$this->assertEquals($constraint, $restoredConstraint);
}
public function testSerializeInitializesGroupsOptionToDefault()
{
$constraint = new ConstraintA(array(
'property1' => 'foo',
'property2' => 'bar',
));
$constraint = unserialize(serialize($constraint));
$expected = new ConstraintA(array(
'property1' => 'foo',
'property2' => 'bar',
'groups' => 'Default',
));
$this->assertEquals($expected, $constraint);
}
public function testSerializeKeepsCustomGroups()
{
$constraint = new ConstraintA(array(
'property1' => 'foo',
'property2' => 'bar',
'groups' => 'MyGroup',
));
$constraint = unserialize(serialize($constraint));
$this->assertSame(array('MyGroup'), $constraint->groups);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidArgumentException
*/
public function testGetErrorNameForUnknownCode()
{
Constraint::getErrorName(1);
}
}

View file

@ -1,134 +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\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, $message, array(), $root, $propertyPath, null);
}
}

View file

@ -1,55 +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\ConstraintViolation;
class ConstraintViolationTest extends \PHPUnit_Framework_TestCase
{
public function testToStringHandlesArrays()
{
$violation = new ConstraintViolation(
'Array',
'{{ value }}',
array('{{ value }}' => array(1, 2, 3)),
'Root',
'property.path',
null
);
$expected = <<<EOF
Root.property.path:
Array
EOF;
$this->assertSame($expected, (string) $violation);
}
public function testToStringHandlesArrayRoots()
{
$violation = new ConstraintViolation(
'42 cannot be used here',
'this is the message template',
array(),
array('some_value' => 42),
'some_value',
null
);
$expected = <<<EOF
Array.some_value:
42 cannot be used here
EOF;
$this->assertSame($expected, (string) $violation);
}
}

View file

@ -1,177 +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\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraint;
class ComparisonTest_Class
{
protected $value;
public function __construct($value)
{
$this->value = $value;
}
public function __toString()
{
return (string) $this->value;
}
}
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
abstract class AbstractComparisonValidatorTestCase extends AbstractConstraintValidatorTest
{
protected static function addPhp5Dot5Comparisons(array $comparisons)
{
if (PHP_VERSION_ID < 50500) {
return $comparisons;
}
$result = $comparisons;
// Duplicate all tests involving DateTime objects to be tested with
// DateTimeImmutable objects as well
foreach ($comparisons as $comparison) {
$add = false;
foreach ($comparison as $i => $value) {
if ($value instanceof \DateTime) {
$comparison[$i] = new \DateTimeImmutable(
$value->format('Y-m-d H:i:s.u e'),
$value->getTimezone()
);
$add = true;
} elseif ('DateTime' === $value) {
$comparison[$i] = 'DateTimeImmutable';
$add = true;
}
}
if ($add) {
$result[] = $comparison;
}
}
return $result;
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testThrowsConstraintExceptionIfNoValueOrProperty()
{
$comparison = $this->createConstraint(array());
$this->validator->validate('some value', $comparison);
}
/**
* @dataProvider provideAllValidComparisons
*
* @param mixed $dirtyValue
* @param mixed $comparisonValue
*/
public function testValidComparisonToValue($dirtyValue, $comparisonValue)
{
$constraint = $this->createConstraint(array('value' => $comparisonValue));
$this->validator->validate($dirtyValue, $constraint);
$this->assertNoViolation();
}
/**
* @return array
*/
public function provideAllValidComparisons()
{
// The provider runs before setUp(), so we need to manually fix
// the default timezone
$this->setDefaultTimezone('UTC');
$comparisons = self::addPhp5Dot5Comparisons($this->provideValidComparisons());
$this->restoreDefaultTimezone();
return $comparisons;
}
/**
* @return array
*/
abstract public function provideValidComparisons();
/**
* @dataProvider provideAllInvalidComparisons
*
* @param mixed $dirtyValue
* @param mixed $dirtyValueAsString
* @param mixed $comparedValue
* @param mixed $comparedValueString
* @param string $comparedValueType
*/
public function testInvalidComparisonToValue($dirtyValue, $dirtyValueAsString, $comparedValue, $comparedValueString, $comparedValueType)
{
// Conversion of dates to string differs between ICU versions
// Make sure we have the correct version loaded
if ($dirtyValue instanceof \DateTime || $dirtyValue instanceof \DateTimeInterface) {
IntlTestHelper::requireIntl($this);
if (PHP_VERSION_ID < 50304 && !(extension_loaded('intl') && method_exists('IntlDateFormatter', 'setTimeZone'))) {
$this->markTestSkipped('Intl supports formatting DateTime objects since 5.3.4');
}
}
$constraint = $this->createConstraint(array('value' => $comparedValue));
$constraint->message = 'Constraint Message';
$this->validator->validate($dirtyValue, $constraint);
$this->buildViolation('Constraint Message')
->setParameter('{{ value }}', $dirtyValueAsString)
->setParameter('{{ compared_value }}', $comparedValueString)
->setParameter('{{ compared_value_type }}', $comparedValueType)
->assertRaised();
}
/**
* @return array
*/
public function provideAllInvalidComparisons()
{
// The provider runs before setUp(), so we need to manually fix
// the default timezone
$this->setDefaultTimezone('UTC');
$comparisons = self::addPhp5Dot5Comparisons($this->provideInvalidComparisons());
$this->restoreDefaultTimezone();
return $comparisons;
}
/**
* @return array
*/
abstract public function provideInvalidComparisons();
/**
* @param array $options Options for the constraint
*
* @return Constraint
*/
abstract protected function createConstraint(array $options);
}

View file

@ -1,441 +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\Constraint;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Context\ExecutionContext;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
use Symfony\Component\Validator\Context\LegacyExecutionContext;
use Symfony\Component\Validator\ExecutionContextInterface as LegacyExecutionContextInterface;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\PropertyMetadata;
use Symfony\Component\Validator\Validation;
/**
* @since 2.5.3
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractConstraintValidatorTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ExecutionContextInterface
*/
protected $context;
/**
* @var ConstraintValidatorInterface
*/
protected $validator;
protected $group;
protected $metadata;
protected $object;
protected $value;
protected $root;
protected $propertyPath;
protected $constraint;
protected $defaultTimezone;
protected function setUp()
{
$this->group = 'MyGroup';
$this->metadata = null;
$this->object = null;
$this->value = 'InvalidValue';
$this->root = 'root';
$this->propertyPath = 'property.path';
// Initialize the context with some constraint so that we can
// successfully build a violation.
$this->constraint = new NotNull();
$this->context = $this->createContext();
$this->validator = $this->createValidator();
$this->validator->initialize($this->context);
\Locale::setDefault('en');
$this->setDefaultTimezone('UTC');
}
protected function tearDown()
{
$this->restoreDefaultTimezone();
}
protected function setDefaultTimezone($defaultTimezone)
{
// Make sure this method can not be called twice before calling
// also restoreDefaultTimezone()
if (null === $this->defaultTimezone) {
$this->defaultTimezone = date_default_timezone_get();
date_default_timezone_set($defaultTimezone);
}
}
protected function restoreDefaultTimezone()
{
if (null !== $this->defaultTimezone) {
date_default_timezone_set($this->defaultTimezone);
$this->defaultTimezone = null;
}
}
protected function createContext()
{
$translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
$validator = $this->getMock('Symfony\Component\Validator\Validator\ValidatorInterface');
$contextualValidator = $this->getMock('Symfony\Component\Validator\Validator\ContextualValidatorInterface');
switch ($this->getApiVersion()) {
case Validation::API_VERSION_2_5:
$context = new ExecutionContext(
$validator,
$this->root,
$translator
);
break;
case Validation::API_VERSION_2_4:
case Validation::API_VERSION_2_5_BC:
$context = new LegacyExecutionContext(
$validator,
$this->root,
$this->getMock('Symfony\Component\Validator\MetadataFactoryInterface'),
$translator
);
break;
default:
throw new \RuntimeException('Invalid API version');
}
$context->setGroup($this->group);
$context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath);
$context->setConstraint($this->constraint);
$validator->expects($this->any())
->method('inContext')
->with($context)
->will($this->returnValue($contextualValidator));
return $context;
}
/**
* @param mixed $message
* @param array $parameters
* @param string $propertyPath
* @param string $invalidValue
* @param null $plural
* @param null $code
*
* @return ConstraintViolation
*
* @deprecated to be removed in Symfony 3.0. Use {@link buildViolation()} instead.
*/
protected function createViolation($message, array $parameters = array(), $propertyPath = 'property.path', $invalidValue = 'InvalidValue', $plural = null, $code = null)
{
return new ConstraintViolation(
null,
$message,
$parameters,
$this->root,
$propertyPath,
$invalidValue,
$plural,
$code,
$this->constraint
);
}
protected function setGroup($group)
{
$this->group = $group;
$this->context->setGroup($group);
}
protected function setObject($object)
{
$this->object = $object;
$this->metadata = is_object($object)
? new ClassMetadata(get_class($object))
: null;
$this->context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath);
}
protected function setProperty($object, $property)
{
$this->object = $object;
$this->metadata = is_object($object)
? new PropertyMetadata(get_class($object), $property)
: null;
$this->context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath);
}
protected function setValue($value)
{
$this->value = $value;
$this->context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath);
}
protected function setRoot($root)
{
$this->root = $root;
$this->context = $this->createContext();
$this->validator->initialize($this->context);
}
protected function setPropertyPath($propertyPath)
{
$this->propertyPath = $propertyPath;
$this->context->setNode($this->value, $this->object, $this->metadata, $this->propertyPath);
}
protected function expectNoValidate()
{
$validator = $this->context->getValidator()->inContext($this->context);
$validator->expects($this->never())
->method('atPath');
$validator->expects($this->never())
->method('validate');
}
protected function expectValidateAt($i, $propertyPath, $value, $group)
{
$validator = $this->context->getValidator()->inContext($this->context);
$validator->expects($this->at(2 * $i))
->method('atPath')
->with($propertyPath)
->will($this->returnValue($validator));
$validator->expects($this->at(2 * $i + 1))
->method('validate')
->with($value, $this->logicalOr(null, array()), $group);
}
protected function expectValidateValueAt($i, $propertyPath, $value, $constraints, $group = null)
{
$contextualValidator = $this->context->getValidator()->inContext($this->context);
$contextualValidator->expects($this->at(2 * $i))
->method('atPath')
->with($propertyPath)
->will($this->returnValue($contextualValidator));
$contextualValidator->expects($this->at(2 * $i + 1))
->method('validate')
->with($value, $constraints, $group);
}
protected function assertNoViolation()
{
$this->assertSame(0, $violationsCount = count($this->context->getViolations()), sprintf('0 violation expected. Got %u.', $violationsCount));
}
/**
* @param mixed $message
* @param array $parameters
* @param string $propertyPath
* @param string $invalidValue
* @param null $plural
* @param null $code
*
* @deprecated To be removed in Symfony 3.0. Use
* {@link buildViolation()} instead.
*/
protected function assertViolation($message, array $parameters = array(), $propertyPath = 'property.path', $invalidValue = 'InvalidValue', $plural = null, $code = null)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the buildViolation() method instead.', E_USER_DEPRECATED);
$this->buildViolation($message)
->setParameters($parameters)
->atPath($propertyPath)
->setInvalidValue($invalidValue)
->setCode($code)
->setPlural($plural)
->assertRaised();
}
/**
* @param array $expected
*
* @deprecated To be removed in Symfony 3.0. Use
* {@link buildViolation()} instead.
*/
protected function assertViolations(array $expected)
{
@trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0. Use the buildViolation() method instead.', E_USER_DEPRECATED);
$violations = $this->context->getViolations();
$this->assertCount(count($expected), $violations);
$i = 0;
foreach ($expected as $violation) {
$this->assertEquals($violation, $violations[$i++]);
}
}
/**
* @param $message
*
* @return ConstraintViolationAssertion
*/
protected function buildViolation($message)
{
return new ConstraintViolationAssertion($this->context, $message, $this->constraint);
}
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
abstract protected function createValidator();
}
/**
* @internal
*/
class ConstraintViolationAssertion
{
/**
* @var LegacyExecutionContextInterface
*/
private $context;
/**
* @var ConstraintViolationAssertion[]
*/
private $assertions;
private $message;
private $parameters = array();
private $invalidValue = 'InvalidValue';
private $propertyPath = 'property.path';
private $translationDomain;
private $plural;
private $code;
private $constraint;
private $cause;
public function __construct(LegacyExecutionContextInterface $context, $message, Constraint $constraint = null, array $assertions = array())
{
$this->context = $context;
$this->message = $message;
$this->constraint = $constraint;
$this->assertions = $assertions;
}
public function atPath($path)
{
$this->propertyPath = $path;
return $this;
}
public function setParameter($key, $value)
{
$this->parameters[$key] = $value;
return $this;
}
public function setParameters(array $parameters)
{
$this->parameters = $parameters;
return $this;
}
public function setTranslationDomain($translationDomain)
{
$this->translationDomain = $translationDomain;
return $this;
}
public function setInvalidValue($invalidValue)
{
$this->invalidValue = $invalidValue;
return $this;
}
public function setPlural($number)
{
$this->plural = $number;
return $this;
}
public function setCode($code)
{
$this->code = $code;
return $this;
}
public function setCause($cause)
{
$this->cause = $cause;
return $this;
}
public function buildNextViolation($message)
{
$assertions = $this->assertions;
$assertions[] = $this;
return new self($this->context, $message, $this->constraint, $assertions);
}
public function assertRaised()
{
$expected = array();
foreach ($this->assertions as $assertion) {
$expected[] = $assertion->getViolation();
}
$expected[] = $this->getViolation();
$violations = iterator_to_array($this->context->getViolations());
\PHPUnit_Framework_Assert::assertSame($expectedCount = count($expected), $violationsCount = count($violations), sprintf('%u violation(s) expected. Got %u.', $expectedCount, $violationsCount));
reset($violations);
foreach ($expected as $violation) {
\PHPUnit_Framework_Assert::assertEquals($violation, current($violations));
next($violations);
}
}
private function getViolation()
{
return new ConstraintViolation(
null,
$this->message,
$this->parameters,
$this->context->getRoot(),
$this->propertyPath,
$this->invalidValue,
$this->plural,
$this->code,
$this->constraint,
$this->cause
);
}
}

View file

@ -1,41 +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\All;
use Symfony\Component\Validator\Constraints\Valid;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class AllTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectNonConstraints()
{
new All(array(
'foo',
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectValidConstraint()
{
new All(array(
new Valid(),
));
}
}

View file

@ -1,93 +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\All;
use Symfony\Component\Validator\Constraints\AllValidator;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Validation;
class AllValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new AllValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new All(new Range(array('min' => 4))));
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testThrowsExceptionIfNotTraversable()
{
$this->validator->validate('foo.barbar', new All(new Range(array('min' => 4))));
}
/**
* @dataProvider getValidArguments
*/
public function testWalkSingleConstraint($array)
{
$constraint = new Range(array('min' => 4));
$i = 0;
foreach ($array as $key => $value) {
$this->expectValidateValueAt($i++, '['.$key.']', $value, array($constraint));
}
$this->validator->validate($array, new All($constraint));
$this->assertNoViolation();
}
/**
* @dataProvider getValidArguments
*/
public function testWalkMultipleConstraints($array)
{
$constraint1 = new Range(array('min' => 4));
$constraint2 = new NotNull();
$constraints = array($constraint1, $constraint2);
$i = 0;
foreach ($array as $key => $value) {
$this->expectValidateValueAt($i++, '['.$key.']', $value, array($constraint1, $constraint2));
}
$this->validator->validate($array, new All($constraints));
$this->assertNoViolation();
}
public function getValidArguments()
{
return array(
array(array(5, 6, 7)),
array(new \ArrayObject(array(5, 6, 7))),
);
}
}

View file

@ -1,69 +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\Blank;
use Symfony\Component\Validator\Constraints\BlankValidator;
use Symfony\Component\Validator\Validation;
class BlankValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new BlankValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Blank());
$this->assertNoViolation();
}
public function testBlankIsValid()
{
$this->validator->validate('', new Blank());
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value, $valueAsString)
{
$constraint = new Blank(array(
'message' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $valueAsString)
->assertRaised();
}
public function getInvalidValues()
{
return array(
array('foobar', '"foobar"'),
array(0, '0'),
array(false, 'false'),
array(1234, '1234'),
);
}
}

View file

@ -1,355 +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\Constraint;
use Symfony\Component\Validator\Constraints\Callback;
use Symfony\Component\Validator\Constraints\CallbackValidator;
use Symfony\Component\Validator\ExecutionContextInterface;
use Symfony\Component\Validator\Validation;
class CallbackValidatorTest_Class
{
public static function validateCallback($object, ExecutionContextInterface $context)
{
$context->addViolation('Callback message', array('{{ value }}' => 'foobar'));
return false;
}
}
class CallbackValidatorTest_Object
{
public function validate(ExecutionContextInterface $context)
{
$context->addViolation('My message', array('{{ value }}' => 'foobar'));
return false;
}
public static function validateStatic($object, ExecutionContextInterface $context)
{
$context->addViolation('Static message', array('{{ value }}' => 'baz'));
return false;
}
}
class CallbackValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CallbackValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Callback());
$this->assertNoViolation();
}
public function testSingleMethod()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback('validate');
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testSingleMethodExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('callback' => 'validate'));
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testSingleStaticMethod()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback('validateStatic');
$this->validator->validate($object, $constraint);
$this->buildViolation('Static message')
->setParameter('{{ value }}', 'baz')
->assertRaised();
}
public function testClosure()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(function ($object, ExecutionContextInterface $context) {
$context->addViolation('My message', array('{{ value }}' => 'foobar'));
return false;
});
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testClosureNullObject()
{
$constraint = new Callback(function ($object, ExecutionContextInterface $context) {
$context->addViolation('My message', array('{{ value }}' => 'foobar'));
return false;
});
$this->validator->validate(null, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testClosureExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
'callback' => function ($object, ExecutionContextInterface $context) {
$context->addViolation('My message', array('{{ value }}' => 'foobar'));
return false;
},
));
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testArrayCallable()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(__CLASS__.'_Class', 'validateCallback'));
$this->validator->validate($object, $constraint);
$this->buildViolation('Callback message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testArrayCallableNullObject()
{
$constraint = new Callback(array(__CLASS__.'_Class', 'validateCallback'));
$this->validator->validate(null, $constraint);
$this->buildViolation('Callback message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
public function testArrayCallableExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
'callback' => array(__CLASS__.'_Class', 'validateCallback'),
));
$this->validator->validate($object, $constraint);
$this->buildViolation('Callback message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
// BC with Symfony < 2.4
/**
* @group legacy
*/
public function testLegacySingleMethodBc()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('validate'));
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
// BC with Symfony < 2.4
/**
* @group legacy
*/
public function testLegacySingleMethodBcExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('methods' => array('validate')));
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
// BC with Symfony < 2.4
/**
* @group legacy
*/
public function testLegacyMultipleMethodsBc()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array('validate', 'validateStatic'));
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->buildNextViolation('Static message')
->setParameter('{{ value }}', 'baz')
->assertRaised();
}
// BC with Symfony < 2.4
/**
* @group legacy
*/
public function testLegacyMultipleMethodsBcExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
'methods' => array('validate', 'validateStatic'),
));
$this->validator->validate($object, $constraint);
$this->buildViolation('My message')
->setParameter('{{ value }}', 'foobar')
->buildNextViolation('Static message')
->setParameter('{{ value }}', 'baz')
->assertRaised();
}
// BC with Symfony < 2.4
/**
* @group legacy
*/
public function testLegacySingleStaticMethodBc()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
array(__CLASS__.'_Class', 'validateCallback'),
));
$this->validator->validate($object, $constraint);
$this->buildViolation('Callback message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
// BC with Symfony < 2.4
/**
* @group legacy
*/
public function testLegacySingleStaticMethodBcExplicitName()
{
$object = new CallbackValidatorTest_Object();
$constraint = new Callback(array(
'methods' => array(array(__CLASS__.'_Class', 'validateCallback')),
));
$this->validator->validate($object, $constraint);
$this->buildViolation('Callback message')
->setParameter('{{ value }}', 'foobar')
->assertRaised();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testExpectValidMethods()
{
$object = new CallbackValidatorTest_Object();
$this->validator->validate($object, new Callback(array('callback' => array('foobar'))));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testExpectValidCallbacks()
{
$object = new CallbackValidatorTest_Object();
$this->validator->validate($object, new Callback(array('callback' => array('foo', 'bar'))));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
* @group legacy
*/
public function testLegacyExpectEitherCallbackOrMethods()
{
$object = new CallbackValidatorTest_Object();
$this->validator->validate($object, new Callback(array(
'callback' => 'validate',
'methods' => array('validateStatic'),
)));
}
public function testConstraintGetTargets()
{
$constraint = new Callback(array());
$targets = array(Constraint::CLASS_CONSTRAINT, Constraint::PROPERTY_CONSTRAINT);
$this->assertEquals($targets, $constraint->getTargets());
}
// Should succeed. Needed when defining constraints as annotations.
public function testNoConstructorArguments()
{
new Callback();
}
public function testAnnotationInvocationSingleValued()
{
$constraint = new Callback(array('value' => 'validateStatic'));
$this->assertEquals(new Callback('validateStatic'), $constraint);
}
public function testAnnotationInvocationMultiValued()
{
$constraint = new Callback(array('value' => array(__CLASS__.'_Class', 'validateCallback')));
$this->assertEquals(new Callback(array(__CLASS__.'_Class', 'validateCallback')), $constraint);
}
}

View file

@ -1,135 +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\CardScheme;
use Symfony\Component\Validator\Constraints\CardSchemeValidator;
use Symfony\Component\Validator\Validation;
class CardSchemeValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CardSchemeValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new CardScheme(array('schemes' => array())));
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new CardScheme(array('schemes' => array())));
$this->assertNoViolation();
}
/**
* @dataProvider getValidNumbers
*/
public function testValidNumbers($scheme, $number)
{
$this->validator->validate($number, new CardScheme(array('schemes' => $scheme)));
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidNumbers
*/
public function testInvalidNumbers($scheme, $number, $code)
{
$constraint = new CardScheme(array(
'schemes' => $scheme,
'message' => 'myMessage',
));
$this->validator->validate($number, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', is_string($number) ? '"'.$number.'"' : $number)
->setCode($code)
->assertRaised();
}
public function getValidNumbers()
{
return array(
array('AMEX', '378282246310005'),
array('AMEX', '371449635398431'),
array('AMEX', '378734493671000'),
array('AMEX', '347298508610146'),
array('CHINA_UNIONPAY', '6228888888888888'),
array('CHINA_UNIONPAY', '62288888888888888'),
array('CHINA_UNIONPAY', '622888888888888888'),
array('CHINA_UNIONPAY', '6228888888888888888'),
array('DINERS', '30569309025904'),
array('DINERS', '36088894118515'),
array('DINERS', '38520000023237'),
array('DISCOVER', '6011111111111117'),
array('DISCOVER', '6011000990139424'),
array('INSTAPAYMENT', '6372476031350068'),
array('INSTAPAYMENT', '6385537775789749'),
array('INSTAPAYMENT', '6393440808445746'),
array('JCB', '3530111333300000'),
array('JCB', '3566002020360505'),
array('JCB', '213112345678901'),
array('JCB', '180012345678901'),
array('LASER', '6304678107004080'),
array('LASER', '6706440607428128629'),
array('LASER', '6771656738314582216'),
array('MAESTRO', '6759744069209'),
array('MAESTRO', '5020507657408074712'),
array('MAESTRO', '5612559223580173965'),
array('MAESTRO', '6759744069209'),
array('MAESTRO', '6759744069209'),
array('MAESTRO', '6594371785970435599'),
array('MASTERCARD', '5555555555554444'),
array('MASTERCARD', '5105105105105100'),
array('VISA', '4111111111111111'),
array('VISA', '4012888888881881'),
array('VISA', '4222222222222'),
array(array('AMEX', 'VISA'), '4111111111111111'),
array(array('AMEX', 'VISA'), '378282246310005'),
array(array('JCB', 'MASTERCARD'), '5105105105105100'),
array(array('VISA', 'MASTERCARD'), '5105105105105100'),
);
}
public function getInvalidNumbers()
{
return array(
array('VISA', '42424242424242424242', CardScheme::INVALID_FORMAT_ERROR),
array('AMEX', '357298508610146', CardScheme::INVALID_FORMAT_ERROR),
array('DINERS', '31569309025904', CardScheme::INVALID_FORMAT_ERROR),
array('DINERS', '37088894118515', CardScheme::INVALID_FORMAT_ERROR),
array('INSTAPAYMENT', '6313440808445746', CardScheme::INVALID_FORMAT_ERROR),
array('CHINA_UNIONPAY', '622888888888888', CardScheme::INVALID_FORMAT_ERROR),
array('CHINA_UNIONPAY', '62288888888888888888', CardScheme::INVALID_FORMAT_ERROR),
array('AMEX', '30569309025904', CardScheme::INVALID_FORMAT_ERROR), // DINERS number
array('AMEX', 'invalid', CardScheme::NOT_NUMERIC_ERROR), // A string
array('AMEX', 0, CardScheme::INVALID_FORMAT_ERROR), // a lone number
array('AMEX', '0', CardScheme::INVALID_FORMAT_ERROR), // a lone number
array('AMEX', '000000000000', CardScheme::INVALID_FORMAT_ERROR), // a lone number
array('DINERS', '3056930', CardScheme::INVALID_FORMAT_ERROR), // only first part of the number
array('DISCOVER', '1117', CardScheme::INVALID_FORMAT_ERROR), // only last 4 digits
);
}
}

View file

@ -1,304 +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\Choice;
use Symfony\Component\Validator\Constraints\ChoiceValidator;
use Symfony\Component\Validator\Validation;
function choice_callback()
{
return array('foo', 'bar');
}
class ChoiceValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new ChoiceValidator();
}
public static function staticCallback()
{
return array('foo', 'bar');
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectArrayIfMultipleIsTrue()
{
$constraint = new Choice(array(
'choices' => array('foo', 'bar'),
'multiple' => true,
));
$this->validator->validate('asdf', $constraint);
}
public function testNullIsValid()
{
$this->validator->validate(null, new Choice(array('choices' => array('foo', 'bar'))));
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testChoicesOrCallbackExpected()
{
$this->validator->validate('foobar', new Choice());
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testValidCallbackExpected()
{
$this->validator->validate('foobar', new Choice(array('callback' => 'abcd')));
}
public function testValidChoiceArray()
{
$constraint = new Choice(array('choices' => array('foo', 'bar')));
$this->validator->validate('bar', $constraint);
$this->assertNoViolation();
}
public function testValidChoiceCallbackFunction()
{
$constraint = new Choice(array('callback' => __NAMESPACE__.'\choice_callback'));
$this->validator->validate('bar', $constraint);
$this->assertNoViolation();
}
public function testValidChoiceCallbackClosure()
{
$constraint = new Choice(array('callback' => function () {
return array('foo', 'bar');
}));
$this->validator->validate('bar', $constraint);
$this->assertNoViolation();
}
public function testValidChoiceCallbackStaticMethod()
{
$constraint = new Choice(array('callback' => array(__CLASS__, 'staticCallback')));
$this->validator->validate('bar', $constraint);
$this->assertNoViolation();
}
public function testValidChoiceCallbackContextMethod()
{
// search $this for "staticCallback"
$this->setObject($this);
$constraint = new Choice(array('callback' => 'staticCallback'));
$this->validator->validate('bar', $constraint);
$this->assertNoViolation();
}
public function testMultipleChoices()
{
$constraint = new Choice(array(
'choices' => array('foo', 'bar', 'baz'),
'multiple' => true,
));
$this->validator->validate(array('baz', 'bar'), $constraint);
$this->assertNoViolation();
}
public function testInvalidChoice()
{
$constraint = new Choice(array(
'choices' => array('foo', 'bar'),
'message' => 'myMessage',
));
$this->validator->validate('baz', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"baz"')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
public function testInvalidChoiceEmptyChoices()
{
$constraint = new Choice(array(
// May happen when the choices are provided dynamically, e.g. from
// the DB or the model
'choices' => array(),
'message' => 'myMessage',
));
$this->validator->validate('baz', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"baz"')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
public function testInvalidChoiceMultiple()
{
$constraint = new Choice(array(
'choices' => array('foo', 'bar'),
'multipleMessage' => 'myMessage',
'multiple' => true,
));
$this->validator->validate(array('foo', 'baz'), $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"baz"')
->setInvalidValue('baz')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
public function testTooFewChoices()
{
$constraint = new Choice(array(
'choices' => array('foo', 'bar', 'moo', 'maa'),
'multiple' => true,
'min' => 2,
'minMessage' => 'myMessage',
));
$value = array('foo');
$this->setValue($value);
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ limit }}', 2)
->setInvalidValue($value)
->setPlural(2)
->setCode(Choice::TOO_FEW_ERROR)
->assertRaised();
}
public function testTooManyChoices()
{
$constraint = new Choice(array(
'choices' => array('foo', 'bar', 'moo', 'maa'),
'multiple' => true,
'max' => 2,
'maxMessage' => 'myMessage',
));
$value = array('foo', 'bar', 'moo');
$this->setValue($value);
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ limit }}', 2)
->setInvalidValue($value)
->setPlural(2)
->setCode(Choice::TOO_MANY_ERROR)
->assertRaised();
}
public function testNonStrict()
{
$constraint = new Choice(array(
'choices' => array(1, 2),
'strict' => false,
));
$this->validator->validate('2', $constraint);
$this->validator->validate(2, $constraint);
$this->assertNoViolation();
}
public function testStrictAllowsExactValue()
{
$constraint = new Choice(array(
'choices' => array(1, 2),
'strict' => true,
));
$this->validator->validate(2, $constraint);
$this->assertNoViolation();
}
public function testStrictDisallowsDifferentType()
{
$constraint = new Choice(array(
'choices' => array(1, 2),
'strict' => true,
'message' => 'myMessage',
));
$this->validator->validate('2', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"2"')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
public function testNonStrictWithMultipleChoices()
{
$constraint = new Choice(array(
'choices' => array(1, 2, 3),
'multiple' => true,
'strict' => false,
));
$this->validator->validate(array('2', 3), $constraint);
$this->assertNoViolation();
}
public function testStrictWithMultipleChoices()
{
$constraint = new Choice(array(
'choices' => array(1, 2, 3),
'multiple' => true,
'strict' => true,
'multipleMessage' => 'myMessage',
));
$this->validator->validate(array(2, '3'), $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"3"')
->setInvalidValue('3')
->setCode(Choice::NO_SUCH_CHOICE_ERROR)
->assertRaised();
}
}

View file

@ -1,112 +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\Collection;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Optional;
use Symfony\Component\Validator\Constraints\Required;
use Symfony\Component\Validator\Constraints\Valid;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class CollectionTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectInvalidFieldsOption()
{
new Collection(array(
'fields' => 'foo',
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectNonConstraints()
{
new Collection(array(
'foo' => 'bar',
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectValidConstraint()
{
new Collection(array(
'foo' => new Valid(),
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectValidConstraintWithinOptional()
{
new Collection(array(
'foo' => new Optional(new Valid()),
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectValidConstraintWithinRequired()
{
new Collection(array(
'foo' => new Required(new Valid()),
));
}
public function testAcceptOptionalConstraintAsOneElementArray()
{
$collection1 = new Collection(array(
'fields' => array(
'alternate_email' => array(
new Optional(new Email()),
),
),
));
$collection2 = new Collection(array(
'fields' => array(
'alternate_email' => new Optional(new Email()),
),
));
$this->assertEquals($collection1, $collection2);
}
public function testAcceptRequiredConstraintAsOneElementArray()
{
$collection1 = new Collection(array(
'fields' => array(
'alternate_email' => array(
new Required(new Email()),
),
),
));
$collection2 = new Collection(array(
'fields' => array(
'alternate_email' => new Required(new Email()),
),
));
$this->assertEquals($collection1, $collection2);
}
}

View file

@ -1,20 +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;
class CollectionValidatorArrayObjectTest extends CollectionValidatorTest
{
public function prepareTestData(array $contents)
{
return new \ArrayObject($contents);
}
}

View file

@ -1,20 +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;
class CollectionValidatorArrayTest extends CollectionValidatorTest
{
public function prepareTestData(array $contents)
{
return $contents;
}
}

View file

@ -1,22 +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\Tests\Fixtures\CustomArrayObject;
class CollectionValidatorCustomArrayObjectTest extends CollectionValidatorTest
{
public function prepareTestData(array $contents)
{
return new CustomArrayObject($contents);
}
}

View file

@ -1,389 +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\Collection;
use Symfony\Component\Validator\Constraints\CollectionValidator;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Optional;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Required;
use Symfony\Component\Validator\Validation;
abstract class CollectionValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CollectionValidator();
}
abstract protected function prepareTestData(array $contents);
public function testNullIsValid()
{
$this->validator->validate(null, new Collection(array('fields' => array(
'foo' => new Range(array('min' => 4)),
))));
$this->assertNoViolation();
}
public function testFieldsAsDefaultOption()
{
$constraint = new Range(array('min' => 4));
$data = $this->prepareTestData(array('foo' => 'foobar'));
$this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint));
$this->validator->validate($data, new Collection(array(
'foo' => $constraint,
)));
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testThrowsExceptionIfNotTraversable()
{
$this->validator->validate('foobar', new Collection(array('fields' => array(
'foo' => new Range(array('min' => 4)),
))));
}
public function testWalkSingleConstraint()
{
$constraint = new Range(array('min' => 4));
$array = array(
'foo' => 3,
'bar' => 5,
);
$i = 0;
foreach ($array as $key => $value) {
$this->expectValidateValueAt($i++, '['.$key.']', $value, array($constraint));
}
$data = $this->prepareTestData($array);
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraint,
'bar' => $constraint,
),
)));
$this->assertNoViolation();
}
public function testWalkMultipleConstraints()
{
$constraints = array(
new Range(array('min' => 4)),
new NotNull(),
);
$array = array(
'foo' => 3,
'bar' => 5,
);
$i = 0;
foreach ($array as $key => $value) {
$this->expectValidateValueAt($i++, '['.$key.']', $value, $constraints);
}
$data = $this->prepareTestData($array);
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraints,
'bar' => $constraints,
),
)));
$this->assertNoViolation();
}
public function testExtraFieldsDisallowed()
{
$constraint = new Range(array('min' => 4));
$data = $this->prepareTestData(array(
'foo' => 5,
'baz' => 6,
));
$this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint));
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraint,
),
'extraFieldsMessage' => 'myMessage',
)));
$this->buildViolation('myMessage')
->setParameter('{{ field }}', '"baz"')
->atPath('property.path[baz]')
->setInvalidValue(6)
->setCode(Collection::NO_SUCH_FIELD_ERROR)
->assertRaised();
}
// bug fix
public function testNullNotConsideredExtraField()
{
$data = $this->prepareTestData(array(
'foo' => null,
));
$constraint = new Range(array('min' => 4));
$this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint));
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraint,
),
)));
$this->assertNoViolation();
}
public function testExtraFieldsAllowed()
{
$data = $this->prepareTestData(array(
'foo' => 5,
'bar' => 6,
));
$constraint = new Range(array('min' => 4));
$this->expectValidateValueAt(0, '[foo]', $data['foo'], array($constraint));
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraint,
),
'allowExtraFields' => true,
)));
$this->assertNoViolation();
}
public function testMissingFieldsDisallowed()
{
$data = $this->prepareTestData(array());
$constraint = new Range(array('min' => 4));
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraint,
),
'missingFieldsMessage' => 'myMessage',
)));
$this->buildViolation('myMessage')
->setParameter('{{ field }}', '"foo"')
->atPath('property.path[foo]')
->setInvalidValue(null)
->setCode(Collection::MISSING_FIELD_ERROR)
->assertRaised();
}
public function testMissingFieldsAllowed()
{
$data = $this->prepareTestData(array());
$constraint = new Range(array('min' => 4));
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => $constraint,
),
'allowMissingFields' => true,
)));
$this->assertNoViolation();
}
public function testOptionalFieldPresent()
{
$data = $this->prepareTestData(array(
'foo' => null,
));
$this->validator->validate($data, new Collection(array(
'foo' => new Optional(),
)));
$this->assertNoViolation();
}
public function testOptionalFieldNotPresent()
{
$data = $this->prepareTestData(array());
$this->validator->validate($data, new Collection(array(
'foo' => new Optional(),
)));
$this->assertNoViolation();
}
public function testOptionalFieldSingleConstraint()
{
$array = array(
'foo' => 5,
);
$constraint = new Range(array('min' => 4));
$this->expectValidateValueAt(0, '[foo]', $array['foo'], array($constraint));
$data = $this->prepareTestData($array);
$this->validator->validate($data, new Collection(array(
'foo' => new Optional($constraint),
)));
$this->assertNoViolation();
}
public function testOptionalFieldMultipleConstraints()
{
$array = array(
'foo' => 5,
);
$constraints = array(
new NotNull(),
new Range(array('min' => 4)),
);
$this->expectValidateValueAt(0, '[foo]', $array['foo'], $constraints);
$data = $this->prepareTestData($array);
$this->validator->validate($data, new Collection(array(
'foo' => new Optional($constraints),
)));
$this->assertNoViolation();
}
public function testRequiredFieldPresent()
{
$data = $this->prepareTestData(array(
'foo' => null,
));
$this->validator->validate($data, new Collection(array(
'foo' => new Required(),
)));
$this->assertNoViolation();
}
public function testRequiredFieldNotPresent()
{
$data = $this->prepareTestData(array());
$this->validator->validate($data, new Collection(array(
'fields' => array(
'foo' => new Required(),
),
'missingFieldsMessage' => 'myMessage',
)));
$this->buildViolation('myMessage')
->setParameter('{{ field }}', '"foo"')
->atPath('property.path[foo]')
->setInvalidValue(null)
->setCode(Collection::MISSING_FIELD_ERROR)
->assertRaised();
}
public function testRequiredFieldSingleConstraint()
{
$array = array(
'foo' => 5,
);
$constraint = new Range(array('min' => 4));
$this->expectValidateValueAt(0, '[foo]', $array['foo'], array($constraint));
$data = $this->prepareTestData($array);
$this->validator->validate($data, new Collection(array(
'foo' => new Required($constraint),
)));
$this->assertNoViolation();
}
public function testRequiredFieldMultipleConstraints()
{
$array = array(
'foo' => 5,
);
$constraints = array(
new NotNull(),
new Range(array('min' => 4)),
);
$this->expectValidateValueAt(0, '[foo]', $array['foo'], $constraints);
$data = $this->prepareTestData($array);
$this->validator->validate($data, new Collection(array(
'foo' => new Required($constraints),
)));
$this->assertNoViolation();
}
public function testObjectShouldBeLeftUnchanged()
{
$value = new \ArrayObject(array(
'foo' => 3,
));
$constraint = new Range(array('min' => 2));
$this->expectValidateValueAt(0, '[foo]', $value['foo'], array($constraint));
$this->validator->validate($value, new Collection(array(
'fields' => array(
'foo' => $constraint,
),
)));
$this->assertEquals(array(
'foo' => 3,
), (array) $value);
}
}

View file

@ -1,138 +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\Composite;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotNull;
use Symfony\Component\Validator\Constraints\Valid;
class ConcreteComposite extends Composite
{
public $constraints;
protected function getCompositeOption()
{
return 'constraints';
}
public function getDefaultOption()
{
return 'constraints';
}
}
/**
* @since 2.6
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class CompositeTest extends \PHPUnit_Framework_TestCase
{
public function testMergeNestedGroupsIfNoExplicitParentGroup()
{
$constraint = new ConcreteComposite(array(
new NotNull(array('groups' => 'Default')),
new NotBlank(array('groups' => array('Default', 'Strict'))),
));
$this->assertEquals(array('Default', 'Strict'), $constraint->groups);
$this->assertEquals(array('Default'), $constraint->constraints[0]->groups);
$this->assertEquals(array('Default', 'Strict'), $constraint->constraints[1]->groups);
}
public function testSetImplicitNestedGroupsIfExplicitParentGroup()
{
$constraint = new ConcreteComposite(array(
'constraints' => array(
new NotNull(),
new NotBlank(),
),
'groups' => array('Default', 'Strict'),
));
$this->assertEquals(array('Default', 'Strict'), $constraint->groups);
$this->assertEquals(array('Default', 'Strict'), $constraint->constraints[0]->groups);
$this->assertEquals(array('Default', 'Strict'), $constraint->constraints[1]->groups);
}
public function testExplicitNestedGroupsMustBeSubsetOfExplicitParentGroups()
{
$constraint = new ConcreteComposite(array(
'constraints' => array(
new NotNull(array('groups' => 'Default')),
new NotBlank(array('groups' => 'Strict')),
),
'groups' => array('Default', 'Strict'),
));
$this->assertEquals(array('Default', 'Strict'), $constraint->groups);
$this->assertEquals(array('Default'), $constraint->constraints[0]->groups);
$this->assertEquals(array('Strict'), $constraint->constraints[1]->groups);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testFailIfExplicitNestedGroupsNotSubsetOfExplicitParentGroups()
{
new ConcreteComposite(array(
'constraints' => array(
new NotNull(array('groups' => array('Default', 'Foobar'))),
),
'groups' => array('Default', 'Strict'),
));
}
public function testImplicitGroupNamesAreForwarded()
{
$constraint = new ConcreteComposite(array(
new NotNull(array('groups' => 'Default')),
new NotBlank(array('groups' => 'Strict')),
));
$constraint->addImplicitGroupName('ImplicitGroup');
$this->assertEquals(array('Default', 'Strict', 'ImplicitGroup'), $constraint->groups);
$this->assertEquals(array('Default', 'ImplicitGroup'), $constraint->constraints[0]->groups);
$this->assertEquals(array('Strict'), $constraint->constraints[1]->groups);
}
public function testSingleConstraintsAccepted()
{
$nestedConstraint = new NotNull();
$constraint = new ConcreteComposite($nestedConstraint);
$this->assertEquals(array($nestedConstraint), $constraint->constraints);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testFailIfNoConstraint()
{
new ConcreteComposite(array(
new NotNull(array('groups' => 'Default')),
'NotBlank',
));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testValidCantBeNested()
{
new ConcreteComposite(array(
new Valid(),
));
}
}

View file

@ -1,23 +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;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class CountValidatorArrayTest extends CountValidatorTest
{
protected function createCollection(array $content)
{
return $content;
}
}

View file

@ -1,25 +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\Tests\Fixtures\Countable;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class CountValidatorCountableTest extends CountValidatorTest
{
protected function createCollection(array $content)
{
return new Countable($content);
}
}

View file

@ -1,203 +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\Count;
use Symfony\Component\Validator\Constraints\CountValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class CountValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CountValidator();
}
abstract protected function createCollection(array $content);
public function testNullIsValid()
{
$this->validator->validate(null, new Count(6));
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsCountableType()
{
$this->validator->validate(new \stdClass(), new Count(5));
}
public function getThreeOrLessElements()
{
return array(
array($this->createCollection(array(1))),
array($this->createCollection(array(1, 2))),
array($this->createCollection(array(1, 2, 3))),
array($this->createCollection(array('a' => 1, 'b' => 2, 'c' => 3))),
);
}
public function getFourElements()
{
return array(
array($this->createCollection(array(1, 2, 3, 4))),
array($this->createCollection(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4))),
);
}
public function getFiveOrMoreElements()
{
return array(
array($this->createCollection(array(1, 2, 3, 4, 5))),
array($this->createCollection(array(1, 2, 3, 4, 5, 6))),
array($this->createCollection(array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5))),
);
}
/**
* @dataProvider getThreeOrLessElements
*/
public function testValidValuesMax($value)
{
$constraint = new Count(array('max' => 3));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getFiveOrMoreElements
*/
public function testValidValuesMin($value)
{
$constraint = new Count(array('min' => 5));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getFourElements
*/
public function testValidValuesExact($value)
{
$constraint = new Count(4);
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getFiveOrMoreElements
*/
public function testTooManyValues($value)
{
$constraint = new Count(array(
'max' => 4,
'maxMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ count }}', count($value))
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Count::TOO_MANY_ERROR)
->assertRaised();
}
/**
* @dataProvider getThreeOrLessElements
*/
public function testTooFewValues($value)
{
$constraint = new Count(array(
'min' => 4,
'minMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ count }}', count($value))
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Count::TOO_FEW_ERROR)
->assertRaised();
}
/**
* @dataProvider getFiveOrMoreElements
*/
public function testTooManyValuesExact($value)
{
$constraint = new Count(array(
'min' => 4,
'max' => 4,
'exactMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ count }}', count($value))
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Count::TOO_MANY_ERROR)
->assertRaised();
}
/**
* @dataProvider getThreeOrLessElements
*/
public function testTooFewValuesExact($value)
{
$constraint = new Count(array(
'min' => 4,
'max' => 4,
'exactMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ count }}', count($value))
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Count::TOO_FEW_ERROR)
->assertRaised();
}
public function testDefaultOption()
{
$constraint = new Count(5);
$this->assertEquals(5, $constraint->min);
$this->assertEquals(5, $constraint->max);
}
}

View file

@ -1,109 +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\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Country;
use Symfony\Component\Validator\Constraints\CountryValidator;
use Symfony\Component\Validator\Validation;
class CountryValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CountryValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Country());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Country());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Country());
}
/**
* @dataProvider getValidCountries
*/
public function testValidCountries($country)
{
$this->validator->validate($country, new Country());
$this->assertNoViolation();
}
public function getValidCountries()
{
return array(
array('GB'),
array('AT'),
array('MY'),
);
}
/**
* @dataProvider getInvalidCountries
*/
public function testInvalidCountries($country)
{
$constraint = new Country(array(
'message' => 'myMessage',
));
$this->validator->validate($country, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$country.'"')
->assertRaised();
}
public function getInvalidCountries()
{
return array(
array('foobar'),
array('EN'),
);
}
public function testValidateUsingCountrySpecificLocale()
{
// in order to test with "en_GB"
IntlTestHelper::requireFullIntl($this);
\Locale::setDefault('en_GB');
$existingCountry = 'GB';
$this->validator->validate($existingCountry, new Country());
$this->assertNoViolation();
}
}

View file

@ -1,111 +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\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Currency;
use Symfony\Component\Validator\Constraints\CurrencyValidator;
use Symfony\Component\Validator\Validation;
class CurrencyValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new CurrencyValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Currency());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Currency());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Currency());
}
/**
* @dataProvider getValidCurrencies
*/
public function testValidCurrencies($currency)
{
$this->validator->validate($currency, new Currency());
$this->assertNoViolation();
}
/**
* @dataProvider getValidCurrencies
**/
public function testValidCurrenciesWithCountrySpecificLocale($currency)
{
IntlTestHelper::requireFullIntl($this);
\Locale::setDefault('en_GB');
$this->validator->validate($currency, new Currency());
$this->assertNoViolation();
}
public function getValidCurrencies()
{
return array(
array('EUR'),
array('USD'),
array('SIT'),
array('AUD'),
array('CAD'),
);
}
/**
* @dataProvider getInvalidCurrencies
*/
public function testInvalidCurrencies($currency)
{
$constraint = new Currency(array(
'message' => 'myMessage',
));
$this->validator->validate($currency, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$currency.'"')
->assertRaised();
}
public function getInvalidCurrencies()
{
return array(
array('EN'),
array('foobar'),
);
}
}

View file

@ -1,110 +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\DateTime;
use Symfony\Component\Validator\Constraints\DateTimeValidator;
use Symfony\Component\Validator\Validation;
class DateTimeValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new DateTimeValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new DateTime());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new DateTime());
$this->assertNoViolation();
}
public function testDateTimeClassIsValid()
{
$this->validator->validate(new \DateTime(), new DateTime());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new DateTime());
}
/**
* @dataProvider getValidDateTimes
*/
public function testValidDateTimes($dateTime)
{
$this->validator->validate($dateTime, new DateTime());
$this->assertNoViolation();
}
public function getValidDateTimes()
{
return array(
array('2010-01-01 01:02:03'),
array('1955-12-12 00:00:00'),
array('2030-05-31 23:59:59'),
);
}
/**
* @dataProvider getInvalidDateTimes
*/
public function testInvalidDateTimes($dateTime, $code)
{
$constraint = new DateTime(array(
'message' => 'myMessage',
));
$this->validator->validate($dateTime, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$dateTime.'"')
->setCode($code)
->assertRaised();
}
public function getInvalidDateTimes()
{
return array(
array('foobar', DateTime::INVALID_FORMAT_ERROR),
array('2010-01-01', DateTime::INVALID_FORMAT_ERROR),
array('00:00:00', DateTime::INVALID_FORMAT_ERROR),
array('2010-01-01 00:00', DateTime::INVALID_FORMAT_ERROR),
array('2010-13-01 00:00:00', DateTime::INVALID_DATE_ERROR),
array('2010-04-32 00:00:00', DateTime::INVALID_DATE_ERROR),
array('2010-02-29 00:00:00', DateTime::INVALID_DATE_ERROR),
array('2010-01-01 24:00:00', DateTime::INVALID_TIME_ERROR),
array('2010-01-01 00:60:00', DateTime::INVALID_TIME_ERROR),
array('2010-01-01 00:00:60', DateTime::INVALID_TIME_ERROR),
);
}
}

View file

@ -1,106 +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\Date;
use Symfony\Component\Validator\Constraints\DateValidator;
use Symfony\Component\Validator\Validation;
class DateValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new DateValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Date());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Date());
$this->assertNoViolation();
}
public function testDateTimeClassIsValid()
{
$this->validator->validate(new \DateTime(), new Date());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Date());
}
/**
* @dataProvider getValidDates
*/
public function testValidDates($date)
{
$this->validator->validate($date, new Date());
$this->assertNoViolation();
}
public function getValidDates()
{
return array(
array('2010-01-01'),
array('1955-12-12'),
array('2030-05-31'),
);
}
/**
* @dataProvider getInvalidDates
*/
public function testInvalidDates($date, $code)
{
$constraint = new Date(array(
'message' => 'myMessage',
));
$this->validator->validate($date, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$date.'"')
->setCode($code)
->assertRaised();
}
public function getInvalidDates()
{
return array(
array('foobar', Date::INVALID_FORMAT_ERROR),
array('foobar 2010-13-01', Date::INVALID_FORMAT_ERROR),
array('2010-13-01 foobar', Date::INVALID_FORMAT_ERROR),
array('2010-13-01', Date::INVALID_DATE_ERROR),
array('2010-04-32', Date::INVALID_DATE_ERROR),
array('2010-02-29', Date::INVALID_DATE_ERROR),
);
}
}

View file

@ -1,106 +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\Email;
use Symfony\Component\Validator\Constraints\EmailValidator;
use Symfony\Component\Validator\Validation;
class EmailValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new EmailValidator(false);
}
public function testNullIsValid()
{
$this->validator->validate(null, new Email());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Email());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Email());
}
/**
* @dataProvider getValidEmails
*/
public function testValidEmails($email)
{
$this->validator->validate($email, new Email());
$this->assertNoViolation();
}
public function getValidEmails()
{
return array(
array('fabien@symfony.com'),
array('example@example.co.uk'),
array('fabien_potencier@example.fr'),
);
}
/**
* @dataProvider getInvalidEmails
*/
public function testInvalidEmails($email)
{
$constraint = new Email(array(
'message' => 'myMessage',
));
$this->validator->validate($email, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$email.'"')
->setCode(Email::INVALID_FORMAT_ERROR)
->assertRaised();
}
public function getInvalidEmails()
{
return array(
array('example'),
array('example@'),
array('example@localhost'),
array('foo@example.com bar'),
);
}
public function testStrict()
{
$constraint = new Email(array('strict' => true));
$this->validator->validate('example@localhost', $constraint);
$this->assertNoViolation();
}
}

View file

@ -1,69 +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\EqualTo;
use Symfony\Component\Validator\Constraints\EqualToValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class EqualToValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new EqualToValidator();
}
protected function createConstraint(array $options)
{
return new EqualTo($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(3, 3),
array(3, '3'),
array('a', 'a'),
array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
array(new \DateTime('2000-01-01'), '2000-01-01'),
array(new \DateTime('2000-01-01 UTC'), '2000-01-01 UTC'),
array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)),
array(null, 1),
);
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(1, '1', 2, '2', 'integer'),
array('22', '"22"', '333', '"333"', 'string'),
array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2001-01-01 UTC'), 'Jan 1, 2001, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
);
}
}

View file

@ -1,214 +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\PropertyAccess\PropertyAccess;
use Symfony\Component\Validator\Constraints\Expression;
use Symfony\Component\Validator\Constraints\ExpressionValidator;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Validation;
class ExpressionValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new ExpressionValidator(PropertyAccess::createPropertyAccessor());
}
public function testExpressionIsEvaluatedWithNullValue()
{
$constraint = new Expression(array(
'expression' => 'false',
'message' => 'myMessage',
));
$this->validator->validate(null, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'null')
->assertRaised();
}
public function testExpressionIsEvaluatedWithEmptyStringValue()
{
$constraint = new Expression(array(
'expression' => 'false',
'message' => 'myMessage',
));
$this->validator->validate('', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '""')
->assertRaised();
}
public function testSucceedingExpressionAtObjectLevel()
{
$constraint = new Expression('this.data == 1');
$object = new Entity();
$object->data = '1';
$this->setObject($object);
$this->validator->validate($object, $constraint);
$this->assertNoViolation();
}
public function testFailingExpressionAtObjectLevel()
{
$constraint = new Expression(array(
'expression' => 'this.data == 1',
'message' => 'myMessage',
));
$object = new Entity();
$object->data = '2';
$this->setObject($object);
$this->validator->validate($object, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'object')
->assertRaised();
}
public function testSucceedingExpressionAtPropertyLevel()
{
$constraint = new Expression('value == this.data');
$object = new Entity();
$object->data = '1';
$this->setRoot($object);
$this->setPropertyPath('data');
$this->setProperty($object, 'data');
$this->validator->validate('1', $constraint);
$this->assertNoViolation();
}
public function testFailingExpressionAtPropertyLevel()
{
$constraint = new Expression(array(
'expression' => 'value == this.data',
'message' => 'myMessage',
));
$object = new Entity();
$object->data = '1';
$this->setRoot($object);
$this->setPropertyPath('data');
$this->setProperty($object, 'data');
$this->validator->validate('2', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"2"')
->atPath('data')
->assertRaised();
}
public function testSucceedingExpressionAtNestedPropertyLevel()
{
$constraint = new Expression('value == this.data');
$object = new Entity();
$object->data = '1';
$root = new Entity();
$root->reference = $object;
$this->setRoot($root);
$this->setPropertyPath('reference.data');
$this->setProperty($object, 'data');
$this->validator->validate('1', $constraint);
$this->assertNoViolation();
}
public function testFailingExpressionAtNestedPropertyLevel()
{
$constraint = new Expression(array(
'expression' => 'value == this.data',
'message' => 'myMessage',
));
$object = new Entity();
$object->data = '1';
$root = new Entity();
$root->reference = $object;
$this->setRoot($root);
$this->setPropertyPath('reference.data');
$this->setProperty($object, 'data');
$this->validator->validate('2', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"2"')
->atPath('reference.data')
->assertRaised();
}
/**
* When validatePropertyValue() is called with a class name
* https://github.com/symfony/symfony/pull/11498.
*/
public function testSucceedingExpressionAtPropertyLevelWithoutRoot()
{
$constraint = new Expression('value == "1"');
$this->setRoot('1');
$this->setPropertyPath('');
$this->setProperty(null, 'property');
$this->validator->validate('1', $constraint);
$this->assertNoViolation();
}
/**
* When validatePropertyValue() is called with a class name
* https://github.com/symfony/symfony/pull/11498.
*/
public function testFailingExpressionAtPropertyLevelWithoutRoot()
{
$constraint = new Expression(array(
'expression' => 'value == "1"',
'message' => 'myMessage',
));
$this->setRoot('2');
$this->setPropertyPath('');
$this->setProperty(null, 'property');
$this->validator->validate('2', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"2"')
->atPath('')
->assertRaised();
}
}

View file

@ -1,152 +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\File;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
class FileTest extends \PHPUnit_Framework_TestCase
{
/**
* @param mixed $maxSize
* @param int $bytes
* @param bool $binaryFormat
* @dataProvider provideValidSizes
*/
public function testMaxSize($maxSize, $bytes, $binaryFormat)
{
$file = new File(array('maxSize' => $maxSize));
$this->assertSame($bytes, $file->maxSize);
$this->assertSame($binaryFormat, $file->binaryFormat);
}
/**
* @dataProvider provideValidSizes
*
* @param int|string $maxSize
* @param int $bytes
* @param string $binaryFormat
*/
public function testMaxSizeCanBeSetAfterInitialization($maxSize, $bytes, $binaryFormat)
{
$file = new File();
$file->maxSize = $maxSize;
$this->assertSame($bytes, $file->maxSize);
$this->assertSame($binaryFormat, $file->binaryFormat);
}
/**
* @dataProvider provideInvalidSizes
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*
* @param int|string $maxSize
*/
public function testInvalidValueForMaxSizeThrowsExceptionAfterInitialization($maxSize)
{
$file = new File(array('maxSize' => 1000));
$file->maxSize = $maxSize;
}
/**
* @dataProvider provideInvalidSizes
*
* @param int|string $maxSize
*/
public function testMaxSizeCannotBeSetToInvalidValueAfterInitialization($maxSize)
{
$file = new File(array('maxSize' => 1000));
try {
$file->maxSize = $maxSize;
} catch (ConstraintDefinitionException $e) {
}
$this->assertSame(1000, $file->maxSize);
}
/**
* @param mixed $maxSize
* @dataProvider provideInValidSizes
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalideMaxSize($maxSize)
{
$file = new File(array('maxSize' => $maxSize));
}
/**
* @return array
*/
public function provideValidSizes()
{
return array(
array('500', 500, false),
array(12300, 12300, false),
array('1ki', 1024, true),
array('1KI', 1024, true),
array('2k', 2000, false),
array('2K', 2000, false),
array('1mi', 1048576, true),
array('1MI', 1048576, true),
array('3m', 3000000, false),
array('3M', 3000000, false),
);
}
/**
* @return array
*/
public function provideInvalidSizes()
{
return array(
array('+100'),
array('foo'),
array('1Ko'),
array('1kio'),
array('1G'),
array('1Gi'),
);
}
/**
* @param mixed $maxSize
* @param bool $guessedFormat
* @param bool $binaryFormat
* @dataProvider provideFormats
*/
public function testBinaryFormat($maxSize, $guessedFormat, $binaryFormat)
{
$file = new File(array('maxSize' => $maxSize, 'binaryFormat' => $guessedFormat));
$this->assertSame($binaryFormat, $file->binaryFormat);
}
/**
* @return array
*/
public function provideFormats()
{
return array(
array(100, null, false),
array(100, true, true),
array(100, false, false),
array('100K', null, false),
array('100K', true, true),
array('100K', false, false),
array('100Ki', null, true),
array('100Ki', true, true),
array('100Ki', false, false),
);
}
}

View file

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

View file

@ -1,36 +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\File;
class FileValidatorPathTest extends FileValidatorTest
{
protected function getFile($filename)
{
return $filename;
}
public function testFileNotFound()
{
$constraint = new File(array(
'notFoundMessage' => 'myMessage',
));
$this->validator->validate('foobar', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ file }}', '"foobar"')
->setCode(File::NOT_FOUND_ERROR)
->assertRaised();
}
}

View file

@ -1,477 +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\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\FileValidator;
use Symfony\Component\Validator\Validation;
abstract class FileValidatorTest extends AbstractConstraintValidatorTest
{
protected $path;
protected $file;
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new FileValidator();
}
protected function setUp()
{
parent::setUp();
$this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'FileValidatorTest';
$this->file = fopen($this->path, 'w');
fwrite($this->file, ' ', 1);
}
protected function tearDown()
{
parent::tearDown();
if (is_resource($this->file)) {
fclose($this->file);
}
if (file_exists($this->path)) {
unlink($this->path);
}
$this->path = null;
$this->file = null;
}
public function testNullIsValid()
{
$this->validator->validate(null, new File());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new File());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleTypeOrFile()
{
$this->validator->validate(new \stdClass(), new File());
}
public function testValidFile()
{
$this->validator->validate($this->path, new File());
$this->assertNoViolation();
}
public function testValidUploadedfile()
{
$file = new UploadedFile($this->path, 'originalName', null, null, null, true);
$this->validator->validate($file, new File());
$this->assertNoViolation();
}
public function provideMaxSizeExceededTests()
{
// We have various interesting limit - size combinations to test.
// Assume a limit of 1000 bytes (1 kB). Then the following table
// lists the violation messages for different file sizes:
// -----------+--------------------------------------------------------
// Size | Violation Message
// -----------+--------------------------------------------------------
// 1000 bytes | No violation
// 1001 bytes | "Size of 1001 bytes exceeded limit of 1000 bytes"
// 1004 bytes | "Size of 1004 bytes exceeded limit of 1000 bytes"
// | NOT: "Size of 1 kB exceeded limit of 1 kB"
// 1005 bytes | "Size of 1.01 kB exceeded limit of 1 kB"
// -----------+--------------------------------------------------------
// As you see, we have two interesting borders:
// 1000/1001 - The border as of which a violation occurs
// 1004/1005 - The border as of which the message can be rounded to kB
// Analogous for kB/MB.
// Prior to Symfony 2.5, violation messages are always displayed in the
// same unit used to specify the limit.
// As of Symfony 2.5, the above logic is implemented.
return array(
// limit in bytes
array(1001, 1000, '1001', '1000', 'bytes'),
array(1004, 1000, '1004', '1000', 'bytes'),
array(1005, 1000, '1.01', '1', 'kB'),
array(1000001, 1000000, '1000001', '1000000', 'bytes'),
array(1004999, 1000000, '1005', '1000', 'kB'),
array(1005000, 1000000, '1.01', '1', 'MB'),
// limit in kB
array(1001, '1k', '1001', '1000', 'bytes'),
array(1004, '1k', '1004', '1000', 'bytes'),
array(1005, '1k', '1.01', '1', 'kB'),
array(1000001, '1000k', '1000001', '1000000', 'bytes'),
array(1004999, '1000k', '1005', '1000', 'kB'),
array(1005000, '1000k', '1.01', '1', 'MB'),
// limit in MB
array(1000001, '1M', '1000001', '1000000', 'bytes'),
array(1004999, '1M', '1005', '1000', 'kB'),
array(1005000, '1M', '1.01', '1', 'MB'),
// limit in KiB
array(1025, '1Ki', '1025', '1024', 'bytes'),
array(1029, '1Ki', '1029', '1024', 'bytes'),
array(1030, '1Ki', '1.01', '1', 'KiB'),
array(1048577, '1024Ki', '1048577', '1048576', 'bytes'),
array(1053818, '1024Ki', '1029.12', '1024', 'KiB'),
array(1053819, '1024Ki', '1.01', '1', 'MiB'),
// limit in MiB
array(1048577, '1Mi', '1048577', '1048576', 'bytes'),
array(1053818, '1Mi', '1029.12', '1024', 'KiB'),
array(1053819, '1Mi', '1.01', '1', 'MiB'),
);
}
/**
* @dataProvider provideMaxSizeExceededTests
*/
public function testMaxSizeExceeded($bytesWritten, $limit, $sizeAsString, $limitAsString, $suffix)
{
fseek($this->file, $bytesWritten - 1, SEEK_SET);
fwrite($this->file, '0');
fclose($this->file);
$constraint = new File(array(
'maxSize' => $limit,
'maxSizeMessage' => 'myMessage',
));
$this->validator->validate($this->getFile($this->path), $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ limit }}', $limitAsString)
->setParameter('{{ size }}', $sizeAsString)
->setParameter('{{ suffix }}', $suffix)
->setParameter('{{ file }}', '"'.$this->path.'"')
->setCode(File::TOO_LARGE_ERROR)
->assertRaised();
}
public function provideMaxSizeNotExceededTests()
{
return array(
// limit in bytes
array(1000, 1000),
array(1000000, 1000000),
// limit in kB
array(1000, '1k'),
array(1000000, '1000k'),
// limit in MB
array(1000000, '1M'),
// limit in KiB
array(1024, '1Ki'),
array(1048576, '1024Ki'),
// limit in MiB
array(1048576, '1Mi'),
);
}
/**
* @dataProvider provideMaxSizeNotExceededTests
*/
public function testMaxSizeNotExceeded($bytesWritten, $limit)
{
fseek($this->file, $bytesWritten - 1, SEEK_SET);
fwrite($this->file, '0');
fclose($this->file);
$constraint = new File(array(
'maxSize' => $limit,
'maxSizeMessage' => 'myMessage',
));
$this->validator->validate($this->getFile($this->path), $constraint);
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMaxSize()
{
$constraint = new File(array(
'maxSize' => '1abc',
));
$this->validator->validate($this->path, $constraint);
}
public function provideBinaryFormatTests()
{
return array(
array(11, 10, null, '11', '10', 'bytes'),
array(11, 10, true, '11', '10', 'bytes'),
array(11, 10, false, '11', '10', 'bytes'),
// round(size) == 1.01kB, limit == 1kB
array(ceil(1000 * 1.01), 1000, null, '1.01', '1', 'kB'),
array(ceil(1000 * 1.01), '1k', null, '1.01', '1', 'kB'),
array(ceil(1024 * 1.01), '1Ki', null, '1.01', '1', 'KiB'),
array(ceil(1024 * 1.01), 1024, true, '1.01', '1', 'KiB'),
array(ceil(1024 * 1.01 * 1000), '1024k', true, '1010', '1000', 'KiB'),
array(ceil(1024 * 1.01), '1Ki', true, '1.01', '1', 'KiB'),
array(ceil(1000 * 1.01), 1000, false, '1.01', '1', 'kB'),
array(ceil(1000 * 1.01), '1k', false, '1.01', '1', 'kB'),
array(ceil(1024 * 1.01 * 10), '10Ki', false, '10.34', '10.24', 'kB'),
);
}
/**
* @dataProvider provideBinaryFormatTests
*/
public function testBinaryFormat($bytesWritten, $limit, $binaryFormat, $sizeAsString, $limitAsString, $suffix)
{
fseek($this->file, $bytesWritten - 1, SEEK_SET);
fwrite($this->file, '0');
fclose($this->file);
$constraint = new File(array(
'maxSize' => $limit,
'binaryFormat' => $binaryFormat,
'maxSizeMessage' => 'myMessage',
));
$this->validator->validate($this->getFile($this->path), $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ limit }}', $limitAsString)
->setParameter('{{ size }}', $sizeAsString)
->setParameter('{{ suffix }}', $suffix)
->setParameter('{{ file }}', '"'.$this->path.'"')
->setCode(File::TOO_LARGE_ERROR)
->assertRaised();
}
public function testValidMimeType()
{
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
->setConstructorArgs(array(__DIR__.'/Fixtures/foo'))
->getMock();
$file
->expects($this->once())
->method('getPathname')
->will($this->returnValue($this->path));
$file
->expects($this->once())
->method('getMimeType')
->will($this->returnValue('image/jpg'));
$constraint = new File(array(
'mimeTypes' => array('image/png', 'image/jpg'),
));
$this->validator->validate($file, $constraint);
$this->assertNoViolation();
}
public function testValidWildcardMimeType()
{
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
->setConstructorArgs(array(__DIR__.'/Fixtures/foo'))
->getMock();
$file
->expects($this->once())
->method('getPathname')
->will($this->returnValue($this->path));
$file
->expects($this->once())
->method('getMimeType')
->will($this->returnValue('image/jpg'));
$constraint = new File(array(
'mimeTypes' => array('image/*'),
));
$this->validator->validate($file, $constraint);
$this->assertNoViolation();
}
public function testInvalidMimeType()
{
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
->setConstructorArgs(array(__DIR__.'/Fixtures/foo'))
->getMock();
$file
->expects($this->once())
->method('getPathname')
->will($this->returnValue($this->path));
$file
->expects($this->once())
->method('getMimeType')
->will($this->returnValue('application/pdf'));
$constraint = new File(array(
'mimeTypes' => array('image/png', 'image/jpg'),
'mimeTypesMessage' => 'myMessage',
));
$this->validator->validate($file, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ type }}', '"application/pdf"')
->setParameter('{{ types }}', '"image/png", "image/jpg"')
->setParameter('{{ file }}', '"'.$this->path.'"')
->setCode(File::INVALID_MIME_TYPE_ERROR)
->assertRaised();
}
public function testInvalidWildcardMimeType()
{
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
->setConstructorArgs(array(__DIR__.'/Fixtures/foo'))
->getMock();
$file
->expects($this->once())
->method('getPathname')
->will($this->returnValue($this->path));
$file
->expects($this->once())
->method('getMimeType')
->will($this->returnValue('application/pdf'));
$constraint = new File(array(
'mimeTypes' => array('image/*', 'image/jpg'),
'mimeTypesMessage' => 'myMessage',
));
$this->validator->validate($file, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ type }}', '"application/pdf"')
->setParameter('{{ types }}', '"image/*", "image/jpg"')
->setParameter('{{ file }}', '"'.$this->path.'"')
->setCode(File::INVALID_MIME_TYPE_ERROR)
->assertRaised();
}
public function testDisallowEmpty()
{
ftruncate($this->file, 0);
$constraint = new File(array(
'disallowEmptyMessage' => 'myMessage',
));
$this->validator->validate($this->getFile($this->path), $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ file }}', '"'.$this->path.'"')
->setCode(File::EMPTY_ERROR)
->assertRaised();
}
/**
* @dataProvider uploadedFileErrorProvider
*/
public function testUploadedFileError($error, $message, array $params = array(), $maxSize = null)
{
$file = new UploadedFile('/path/to/file', 'originalName', 'mime', 0, $error);
$constraint = new File(array(
$message => 'myMessage',
'maxSize' => $maxSize,
));
$this->validator->validate($file, $constraint);
$this->buildViolation('myMessage')
->setParameters($params)
->setCode($error)
->assertRaised();
}
public function uploadedFileErrorProvider()
{
$tests = array(
array(UPLOAD_ERR_FORM_SIZE, 'uploadFormSizeErrorMessage'),
array(UPLOAD_ERR_PARTIAL, 'uploadPartialErrorMessage'),
array(UPLOAD_ERR_NO_FILE, 'uploadNoFileErrorMessage'),
array(UPLOAD_ERR_NO_TMP_DIR, 'uploadNoTmpDirErrorMessage'),
array(UPLOAD_ERR_CANT_WRITE, 'uploadCantWriteErrorMessage'),
array(UPLOAD_ERR_EXTENSION, 'uploadExtensionErrorMessage'),
);
if (class_exists('Symfony\Component\HttpFoundation\File\UploadedFile')) {
// when no maxSize is specified on constraint, it should use the ini value
$tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
'{{ limit }}' => UploadedFile::getMaxFilesize() / 1048576,
'{{ suffix }}' => 'MiB',
));
// it should use the smaller limitation (maxSize option in this case)
$tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
'{{ limit }}' => 1,
'{{ suffix }}' => 'bytes',
), '1');
// it correctly parses the maxSize option and not only uses simple string comparison
// 1000M should be bigger than the ini value
$tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
'{{ limit }}' => UploadedFile::getMaxFilesize() / 1048576,
'{{ suffix }}' => 'MiB',
), '1000M');
// it correctly parses the maxSize option and not only uses simple string comparison
// 1000M should be bigger than the ini value
$tests[] = array(UPLOAD_ERR_INI_SIZE, 'uploadIniSizeErrorMessage', array(
'{{ limit }}' => '0.1',
'{{ suffix }}' => 'MB',
), '100K');
}
return $tests;
}
abstract protected function getFile($filename);
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 801 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 B

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\Constraints;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqualValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class GreaterThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new GreaterThanOrEqualValidator();
}
protected function createConstraint(array $options)
{
return new GreaterThanOrEqual($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(3, 2),
array(1, 1),
array(new \DateTime('2010/01/01'), new \DateTime('2000/01/01')),
array(new \DateTime('2000/01/01'), new \DateTime('2000/01/01')),
array(new \DateTime('2010/01/01'), '2000/01/01'),
array(new \DateTime('2000/01/01'), '2000/01/01'),
array(new \DateTime('2010/01/01 UTC'), '2000/01/01 UTC'),
array(new \DateTime('2000/01/01 UTC'), '2000/01/01 UTC'),
array('a', 'a'),
array('z', 'a'),
array(null, 1),
);
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(1, '1', 2, '2', 'integer'),
array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2005/01/01'), 'Jan 1, 2005, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', '2005/01/01', 'Jan 1, 2005, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01 UTC'), 'Jan 1, 2000, 12:00 AM', '2005/01/01 UTC', 'Jan 1, 2005, 12:00 AM', 'DateTime'),
array('b', '"b"', 'c', '"c"', 'string'),
);
}
}

View file

@ -1,74 +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\GreaterThan;
use Symfony\Component\Validator\Constraints\GreaterThanValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class GreaterThanValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new GreaterThanValidator();
}
protected function createConstraint(array $options)
{
return new GreaterThan($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(2, 1),
array(new \DateTime('2005/01/01'), new \DateTime('2001/01/01')),
array(new \DateTime('2005/01/01'), '2001/01/01'),
array(new \DateTime('2005/01/01 UTC'), '2001/01/01 UTC'),
array(new ComparisonTest_Class(5), new ComparisonTest_Class(4)),
array('333', '22'),
array(null, 1),
);
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(1, '1', 2, '2', 'integer'),
array(2, '2', 2, '2', 'integer'),
array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2005/01/01'), 'Jan 1, 2005, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', '2005/01/01', 'Jan 1, 2005, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01'), 'Jan 1, 2000, 12:00 AM', '2000/01/01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01 UTC'), 'Jan 1, 2000, 12:00 AM', '2005/01/01 UTC', 'Jan 1, 2005, 12:00 AM', 'DateTime'),
array(new \DateTime('2000/01/01 UTC'), 'Jan 1, 2000, 12:00 AM', '2000/01/01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
array('22', '"22"', '333', '"333"', 'string'),
array('22', '"22"', '22', '"22"', 'string'),
);
}
}

View file

@ -1,97 +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\GroupSequence;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class GroupSequenceTest extends \PHPUnit_Framework_TestCase
{
public function testCreate()
{
$sequence = new GroupSequence(array('Group 1', 'Group 2'));
$this->assertSame(array('Group 1', 'Group 2'), $sequence->groups);
}
public function testCreateDoctrineStyle()
{
$sequence = new GroupSequence(array('value' => array('Group 1', 'Group 2')));
$this->assertSame(array('Group 1', 'Group 2'), $sequence->groups);
}
/**
* @group legacy
*/
public function testLegacyIterate()
{
$sequence = new GroupSequence(array('Group 1', 'Group 2'));
$this->assertSame(array('Group 1', 'Group 2'), iterator_to_array($sequence));
}
/**
* @group legacy
*/
public function testLegacyCount()
{
$sequence = new GroupSequence(array('Group 1', 'Group 2'));
$this->assertCount(2, $sequence);
}
/**
* @group legacy
*/
public function testLegacyArrayAccess()
{
$sequence = new GroupSequence(array('Group 1', 'Group 2'));
$this->assertSame('Group 1', $sequence[0]);
$this->assertSame('Group 2', $sequence[1]);
$this->assertTrue(isset($sequence[0]));
$this->assertFalse(isset($sequence[2]));
unset($sequence[0]);
$this->assertFalse(isset($sequence[0]));
$sequence[] = 'Group 3';
$this->assertTrue(isset($sequence[2]));
$this->assertSame('Group 3', $sequence[2]);
$sequence[0] = 'Group 1';
$this->assertTrue(isset($sequence[0]));
$this->assertSame('Group 1', $sequence[0]);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\OutOfBoundsException
* @group legacy
*/
public function testLegacyGetExpectsExistingKey()
{
$sequence = new GroupSequence(array('Group 1', 'Group 2'));
$sequence[2];
}
/**
* @group legacy
*/
public function testLegacyUnsetIgnoresNonExistingKeys()
{
$sequence = new GroupSequence(array('Group 1', 'Group 2'));
// should not fail
unset($sequence[2]);
}
}

View file

@ -1,438 +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\Iban;
use Symfony\Component\Validator\Constraints\IbanValidator;
use Symfony\Component\Validator\Validation;
class IbanValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IbanValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Iban());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Iban());
$this->assertNoViolation();
}
/**
* @dataProvider getValidIbans
*/
public function testValidIbans($iban)
{
$this->validator->validate($iban, new Iban());
$this->assertNoViolation();
}
public function getValidIbans()
{
return array(
array('CH9300762011623852957'), // Switzerland without spaces
array('CH93 0076 2011 6238 5295 7'), // Switzerland with multiple spaces
// Country list
// http://www.rbs.co.uk/corporate/international/g0/guide-to-international-business/regulatory-information/iban/iban-example.ashx
array('AL47 2121 1009 0000 0002 3569 8741'), //Albania
array('AD12 0001 2030 2003 5910 0100'), //Andorra
array('AT61 1904 3002 3457 3201'), //Austria
array('AZ21 NABZ 0000 0000 1370 1000 1944'), //Azerbaijan
array('BH67 BMAG 0000 1299 1234 56'), //Bahrain
array('BE62 5100 0754 7061'), //Belgium
array('BA39 1290 0794 0102 8494'), //Bosnia and Herzegovina
array('BG80 BNBG 9661 1020 3456 78'), //Bulgaria
array('HR12 1001 0051 8630 0016 0'), //Croatia
array('CY17 0020 0128 0000 0012 0052 7600'), //Cyprus
array('CZ65 0800 0000 1920 0014 5399'), //Czech Republic
array('DK50 0040 0440 1162 43'), //Denmark
array('EE38 2200 2210 2014 5685'), //Estonia
array('FO97 5432 0388 8999 44'), //Faroe Islands
array('FI21 1234 5600 0007 85'), //Finland
array('FR14 2004 1010 0505 0001 3M02 606'), //France
array('GE29 NB00 0000 0101 9049 17'), //Georgia
array('DE89 3704 0044 0532 0130 00'), //Germany
array('GI75 NWBK 0000 0000 7099 453'), //Gibraltar
array('GR16 0110 1250 0000 0001 2300 695'), //Greece
array('GL56 0444 9876 5432 10'), //Greenland
array('HU42 1177 3016 1111 1018 0000 0000'), //Hungary
array('IS14 0159 2600 7654 5510 7303 39'), //Iceland
array('IE29 AIBK 9311 5212 3456 78'), //Ireland
array('IL62 0108 0000 0009 9999 999'), //Israel
array('IT40 S054 2811 1010 0000 0123 456'), //Italy
array('LV80 BANK 0000 4351 9500 1'), //Latvia
array('LB62 0999 0000 0001 0019 0122 9114'), //Lebanon
array('LI21 0881 0000 2324 013A A'), //Liechtenstein
array('LT12 1000 0111 0100 1000'), //Lithuania
array('LU28 0019 4006 4475 0000'), //Luxembourg
array('MK072 5012 0000 0589 84'), //Macedonia
array('MT84 MALT 0110 0001 2345 MTLC AST0 01S'), //Malta
array('MU17 BOMM 0101 1010 3030 0200 000M UR'), //Mauritius
array('MD24 AG00 0225 1000 1310 4168'), //Moldova
array('MC93 2005 2222 1001 1223 3M44 555'), //Monaco
array('ME25 5050 0001 2345 6789 51'), //Montenegro
array('NL39 RABO 0300 0652 64'), //Netherlands
array('NO93 8601 1117 947'), //Norway
array('PK36 SCBL 0000 0011 2345 6702'), //Pakistan
array('PL60 1020 1026 0000 0422 7020 1111'), //Poland
array('PT50 0002 0123 1234 5678 9015 4'), //Portugal
array('RO49 AAAA 1B31 0075 9384 0000'), //Romania
array('SM86 U032 2509 8000 0000 0270 100'), //San Marino
array('SA03 8000 0000 6080 1016 7519'), //Saudi Arabia
array('RS35 2600 0560 1001 6113 79'), //Serbia
array('SK31 1200 0000 1987 4263 7541'), //Slovak Republic
array('SI56 1910 0000 0123 438'), //Slovenia
array('ES80 2310 0001 1800 0001 2345'), //Spain
array('SE35 5000 0000 0549 1000 0003'), //Sweden
array('CH93 0076 2011 6238 5295 7'), //Switzerland
array('TN59 1000 6035 1835 9847 8831'), //Tunisia
array('TR33 0006 1005 1978 6457 8413 26'), //Turkey
array('AE07 0331 2345 6789 0123 456'), //UAE
array('GB12 CPBK 0892 9965 0449 91'), //United Kingdom
//Extended country list
//http://www.nordea.com/Our+services/International+products+and+services/Cash+Management/IBAN+countries/908462.html
// http://www.swift.com/dsp/resources/documents/IBAN_Registry.pdf
array('AO06000600000100037131174'), //Angola
array('AZ21NABZ00000000137010001944'), //Azerbaijan
array('BH29BMAG1299123456BH00'), //Bahrain
array('BJ11B00610100400271101192591'), //Benin
array('BR9700360305000010009795493P1'), // Brazil
array('BR1800000000141455123924100C2'), // Brazil
array('VG96VPVG0000012345678901'), //British Virgin Islands
array('BF1030134020015400945000643'), //Burkina Faso
array('BI43201011067444'), //Burundi
array('CM2110003001000500000605306'), //Cameroon
array('CV64000300004547069110176'), //Cape Verde
array('FR7630007000110009970004942'), //Central African Republic
array('CG5230011000202151234567890'), //Congo
array('CR0515202001026284066'), //Costa Rica
array('DO28BAGR00000001212453611324'), //Dominican Republic
array('GT82TRAJ01020000001210029690'), //Guatemala
array('IR580540105180021273113007'), //Iran
array('IL620108000000099999999'), //Israel
array('CI05A00060174100178530011852'), //Ivory Coast
array('JO94CBJO0010000000000131000302'), // Jordan
array('KZ176010251000042993'), //Kazakhstan
array('KW74NBOK0000000000001000372151'), //Kuwait
array('LB30099900000001001925579115'), //Lebanon
array('MG4600005030010101914016056'), //Madagascar
array('ML03D00890170001002120000447'), //Mali
array('MR1300012000010000002037372'), //Mauritania
array('MU17BOMM0101101030300200000MUR'), //Mauritius
array('MZ59000100000011834194157'), //Mozambique
array('PS92PALS000000000400123456702'), //Palestinian Territory
array('QA58DOHB00001234567890ABCDEFG'), //Qatar
array('XK051212012345678906'), //Republic of Kosovo
array('PT50000200000163099310355'), //Sao Tome and Principe
array('SA0380000000608010167519'), //Saudi Arabia
array('SN12K00100152000025690007542'), //Senegal
array('TL380080012345678910157'), //Timor-Leste
array('TN5914207207100707129648'), //Tunisia
array('TR330006100519786457841326'), //Turkey
array('AE260211000000230064016'), //United Arab Emirates
);
}
/**
* @dataProvider getIbansWithInvalidFormat
*/
public function testIbansWithInvalidFormat($iban)
{
$this->assertViolationRaised($iban, Iban::INVALID_FORMAT_ERROR);
}
public function getIbansWithInvalidFormat()
{
return array(
array('AL47 2121 1009 0000 0002 3569 874'), //Albania
array('AD12 0001 2030 2003 5910 010'), //Andorra
array('AT61 1904 3002 3457 320'), //Austria
array('AZ21 NABZ 0000 0000 1370 1000 194'), //Azerbaijan
array('AZ21 N1BZ 0000 0000 1370 1000 1944'), //Azerbaijan
array('BH67 BMAG 0000 1299 1234 5'), //Bahrain
array('BH67 B2AG 0000 1299 1234 56'), //Bahrain
array('BE62 5100 0754 7061 2'), //Belgium
array('BA39 1290 0794 0102 8494 4'), //Bosnia and Herzegovina
array('BG80 BNBG 9661 1020 3456 7'), //Bulgaria
array('BG80 B2BG 9661 1020 3456 78'), //Bulgaria
array('HR12 1001 0051 8630 0016 01'), //Croatia
array('CY17 0020 0128 0000 0012 0052 7600 1'), //Cyprus
array('CZ65 0800 0000 1920 0014 5399 1'), //Czech Republic
array('DK50 0040 0440 1162 431'), //Denmark
array('EE38 2200 2210 2014 5685 1'), //Estonia
array('FO97 5432 0388 8999 441'), //Faroe Islands
array('FI21 1234 5600 0007 851'), //Finland
array('FR14 2004 1010 0505 0001 3M02 6061'), //France
array('GE29 NB00 0000 0101 9049 171'), //Georgia
array('DE89 3704 0044 0532 0130 001'), //Germany
array('GI75 NWBK 0000 0000 7099 4531'), //Gibraltar
array('GR16 0110 1250 0000 0001 2300 6951'), //Greece
array('GL56 0444 9876 5432 101'), //Greenland
array('HU42 1177 3016 1111 1018 0000 0000 1'), //Hungary
array('IS14 0159 2600 7654 5510 7303 391'), //Iceland
array('IE29 AIBK 9311 5212 3456 781'), //Ireland
array('IL62 0108 0000 0009 9999 9991'), //Israel
array('IT40 S054 2811 1010 0000 0123 4561'), //Italy
array('LV80 BANK 0000 4351 9500 11'), //Latvia
array('LB62 0999 0000 0001 0019 0122 9114 1'), //Lebanon
array('LI21 0881 0000 2324 013A A1'), //Liechtenstein
array('LT12 1000 0111 0100 1000 1'), //Lithuania
array('LU28 0019 4006 4475 0000 1'), //Luxembourg
array('MK072 5012 0000 0589 84 1'), //Macedonia
array('MT84 MALT 0110 0001 2345 MTLC AST0 01SA'), //Malta
array('MU17 BOMM 0101 1010 3030 0200 000M URA'), //Mauritius
array('MD24 AG00 0225 1000 1310 4168 1'), //Moldova
array('MC93 2005 2222 1001 1223 3M44 5551'), //Monaco
array('ME25 5050 0001 2345 6789 511'), //Montenegro
array('NL39 RABO 0300 0652 641'), //Netherlands
array('NO93 8601 1117 9471'), //Norway
array('PK36 SCBL 0000 0011 2345 6702 1'), //Pakistan
array('PL60 1020 1026 0000 0422 7020 1111 1'), //Poland
array('PT50 0002 0123 1234 5678 9015 41'), //Portugal
array('RO49 AAAA 1B31 0075 9384 0000 1'), //Romania
array('SM86 U032 2509 8000 0000 0270 1001'), //San Marino
array('SA03 8000 0000 6080 1016 7519 1'), //Saudi Arabia
array('RS35 2600 0560 1001 6113 791'), //Serbia
array('SK31 1200 0000 1987 4263 7541 1'), //Slovak Republic
array('SI56 1910 0000 0123 4381'), //Slovenia
array('ES80 2310 0001 1800 0001 2345 1'), //Spain
array('SE35 5000 0000 0549 1000 0003 1'), //Sweden
array('CH93 0076 2011 6238 5295 71'), //Switzerland
array('TN59 1000 6035 1835 9847 8831 1'), //Tunisia
array('TR33 0006 1005 1978 6457 8413 261'), //Turkey
array('AE07 0331 2345 6789 0123 4561'), //UAE
array('GB12 CPBK 0892 9965 0449 911'), //United Kingdom
//Extended country list
array('AO060006000001000371311741'), //Angola
array('AZ21NABZ000000001370100019441'), //Azerbaijan
array('BH29BMAG1299123456BH001'), //Bahrain
array('BJ11B006101004002711011925911'), //Benin
array('BR9700360305000010009795493P11'), // Brazil
array('BR1800000000141455123924100C21'), // Brazil
array('VG96VPVG00000123456789011'), //British Virgin Islands
array('BF10301340200154009450006431'), //Burkina Faso
array('BI432010110674441'), //Burundi
array('CM21100030010005000006053061'), //Cameroon
array('CV640003000045470691101761'), //Cape Verde
array('FR76300070001100099700049421'), //Central African Republic
array('CG52300110002021512345678901'), //Congo
array('CR05152020010262840661'), //Costa Rica
array('DO28BAGR000000012124536113241'), //Dominican Republic
array('GT82TRAJ010200000012100296901'), //Guatemala
array('IR5805401051800212731130071'), //Iran
array('IL6201080000000999999991'), //Israel
array('CI05A000601741001785300118521'), //Ivory Coast
array('JO94CBJO00100000000001310003021'), // Jordan
array('KZ1760102510000429931'), //Kazakhstan
array('KW74NBOK00000000000010003721511'), //Kuwait
array('LB300999000000010019255791151'), //Lebanon
array('MG46000050300101019140160561'), //Madagascar
array('ML03D008901700010021200004471'), //Mali
array('MR13000120000100000020373721'), //Mauritania
array('MU17BOMM0101101030300200000MUR1'), //Mauritius
array('MZ590001000000118341941571'), //Mozambique
array('PS92PALS0000000004001234567021'), //Palestinian Territory
array('QA58DOHB00001234567890ABCDEFG1'), //Qatar
array('XK0512120123456789061'), //Republic of Kosovo
array('PT500002000001630993103551'), //Sao Tome and Principe
array('SA03800000006080101675191'), //Saudi Arabia
array('SN12K001001520000256900075421'), //Senegal
array('TL3800800123456789101571'), //Timor-Leste
array('TN59142072071007071296481'), //Tunisia
array('TR3300061005197864578413261'), //Turkey
array('AE2602110000002300640161'), //United Arab Emirates
);
}
/**
* @dataProvider getIbansWithValidFormatButIncorrectChecksum
*/
public function testIbansWithValidFormatButIncorrectChecksum($iban)
{
$this->assertViolationRaised($iban, Iban::CHECKSUM_FAILED_ERROR);
}
public function getIbansWithValidFormatButIncorrectChecksum()
{
return array(
array('AL47 2121 1009 0000 0002 3569 8742'), //Albania
array('AD12 0001 2030 2003 5910 0101'), //Andorra
array('AT61 1904 3002 3457 3202'), //Austria
array('AZ21 NABZ 0000 0000 1370 1000 1945'), //Azerbaijan
array('BH67 BMAG 0000 1299 1234 57'), //Bahrain
array('BE62 5100 0754 7062'), //Belgium
array('BA39 1290 0794 0102 8495'), //Bosnia and Herzegovina
array('BG80 BNBG 9661 1020 3456 79'), //Bulgaria
array('HR12 1001 0051 8630 0016 1'), //Croatia
array('CY17 0020 0128 0000 0012 0052 7601'), //Cyprus
array('CZ65 0800 0000 1920 0014 5398'), //Czech Republic
array('DK50 0040 0440 1162 44'), //Denmark
array('EE38 2200 2210 2014 5684'), //Estonia
array('FO97 5432 0388 8999 43'), //Faroe Islands
array('FI21 1234 5600 0007 84'), //Finland
array('FR14 2004 1010 0505 0001 3M02 605'), //France
array('GE29 NB00 0000 0101 9049 16'), //Georgia
array('DE89 3704 0044 0532 0130 01'), //Germany
array('GI75 NWBK 0000 0000 7099 452'), //Gibraltar
array('GR16 0110 1250 0000 0001 2300 694'), //Greece
array('GL56 0444 9876 5432 11'), //Greenland
array('HU42 1177 3016 1111 1018 0000 0001'), //Hungary
array('IS14 0159 2600 7654 5510 7303 38'), //Iceland
array('IE29 AIBK 9311 5212 3456 79'), //Ireland
array('IL62 0108 0000 0009 9999 998'), //Israel
array('IT40 S054 2811 1010 0000 0123 457'), //Italy
array('LV80 BANK 0000 4351 9500 2'), //Latvia
array('LB62 0999 0000 0001 0019 0122 9115'), //Lebanon
array('LI21 0881 0000 2324 013A B'), //Liechtenstein
array('LT12 1000 0111 0100 1001'), //Lithuania
array('LU28 0019 4006 4475 0001'), //Luxembourg
array('MK072 5012 0000 0589 85'), //Macedonia
array('MT84 MALT 0110 0001 2345 MTLC AST0 01T'), //Malta
array('MU17 BOMM 0101 1010 3030 0200 000M UP'), //Mauritius
array('MD24 AG00 0225 1000 1310 4169'), //Moldova
array('MC93 2005 2222 1001 1223 3M44 554'), //Monaco
array('ME25 5050 0001 2345 6789 52'), //Montenegro
array('NL39 RABO 0300 0652 65'), //Netherlands
array('NO93 8601 1117 948'), //Norway
array('PK36 SCBL 0000 0011 2345 6703'), //Pakistan
array('PL60 1020 1026 0000 0422 7020 1112'), //Poland
array('PT50 0002 0123 1234 5678 9015 5'), //Portugal
array('RO49 AAAA 1B31 0075 9384 0001'), //Romania
array('SM86 U032 2509 8000 0000 0270 101'), //San Marino
array('SA03 8000 0000 6080 1016 7518'), //Saudi Arabia
array('RS35 2600 0560 1001 6113 78'), //Serbia
array('SK31 1200 0000 1987 4263 7542'), //Slovak Republic
array('SI56 1910 0000 0123 439'), //Slovenia
array('ES80 2310 0001 1800 0001 2346'), //Spain
array('SE35 5000 0000 0549 1000 0004'), //Sweden
array('CH93 0076 2011 6238 5295 8'), //Switzerland
array('TN59 1000 6035 1835 9847 8832'), //Tunisia
array('TR33 0006 1005 1978 6457 8413 27'), //Turkey
array('AE07 0331 2345 6789 0123 457'), //UAE
array('GB12 CPBK 0892 9965 0449 92'), //United Kingdom
//Extended country list
array('AO06000600000100037131175'), //Angola
array('AZ21NABZ00000000137010001945'), //Azerbaijan
array('BH29BMAG1299123456BH01'), //Bahrain
array('BJ11B00610100400271101192592'), //Benin
array('BR9700360305000010009795493P2'), // Brazil
array('BR1800000000141455123924100C3'), // Brazil
array('VG96VPVG0000012345678902'), //British Virgin Islands
array('BF1030134020015400945000644'), //Burkina Faso
array('BI43201011067445'), //Burundi
array('CM2110003001000500000605307'), //Cameroon
array('CV64000300004547069110177'), //Cape Verde
array('FR7630007000110009970004943'), //Central African Republic
array('CG5230011000202151234567891'), //Congo
array('CR0515202001026284067'), //Costa Rica
array('DO28BAGR00000001212453611325'), //Dominican Republic
array('GT82TRAJ01020000001210029691'), //Guatemala
array('IR580540105180021273113008'), //Iran
array('IL620108000000099999998'), //Israel
array('CI05A00060174100178530011853'), //Ivory Coast
array('JO94CBJO0010000000000131000303'), // Jordan
array('KZ176010251000042994'), //Kazakhstan
array('KW74NBOK0000000000001000372152'), //Kuwait
array('LB30099900000001001925579116'), //Lebanon
array('MG4600005030010101914016057'), //Madagascar
array('ML03D00890170001002120000448'), //Mali
array('MR1300012000010000002037373'), //Mauritania
array('MU17BOMM0101101030300200000MUP'), //Mauritius
array('MZ59000100000011834194158'), //Mozambique
array('PS92PALS000000000400123456703'), //Palestinian Territory
array('QA58DOHB00001234567890ABCDEFH'), //Qatar
array('XK051212012345678907'), //Republic of Kosovo
array('PT50000200000163099310356'), //Sao Tome and Principe
array('SA0380000000608010167518'), //Saudi Arabia
array('SN12K00100152000025690007543'), //Senegal
array('TL380080012345678910158'), //Timor-Leste
array('TN5914207207100707129649'), //Tunisia
array('TR330006100519786457841327'), //Turkey
array('AE260211000000230064017'), //United Arab Emirates
);
}
/**
* @dataProvider getUnsupportedCountryCodes
*/
public function testIbansWithUnsupportedCountryCode($countryCode)
{
$this->assertViolationRaised($countryCode.'260211000000230064016', Iban::NOT_SUPPORTED_COUNTRY_CODE_ERROR);
}
public function getUnsupportedCountryCodes()
{
return array(
array('AG'),
array('AI'),
array('AQ'),
array('AS'),
array('AW'),
);
}
public function testIbansWithInvalidCharacters()
{
$this->assertViolationRaised('CH930076201162385295]', Iban::INVALID_CHARACTERS_ERROR);
}
/**
* @dataProvider getIbansWithInvalidCountryCode
*/
public function testIbansWithInvalidCountryCode($iban)
{
$this->assertViolationRaised($iban, Iban::INVALID_COUNTRY_CODE_ERROR);
}
public function getIbansWithInvalidCountryCode()
{
return array(
array('0750447346'),
array('2X0750447346'),
array('A20750447346'),
);
}
private function assertViolationRaised($iban, $code)
{
$constraint = new Iban(array(
'message' => 'myMessage',
));
$this->validator->validate($iban, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$iban.'"')
->setCode($code)
->assertRaised();
}
}

View file

@ -1,89 +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\IdenticalTo;
use Symfony\Component\Validator\Constraints\IdenticalToValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class IdenticalToValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IdenticalToValidator();
}
protected function createConstraint(array $options)
{
return new IdenticalTo($options);
}
public function provideAllValidComparisons()
{
$this->setDefaultTimezone('UTC');
// Don't call addPhp5Dot5Comparisons() automatically, as it does
// not take care of identical objects
$comparisons = $this->provideValidComparisons();
$this->restoreDefaultTimezone();
return $comparisons;
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
$date = new \DateTime('2000-01-01');
$object = new ComparisonTest_Class(2);
$comparisons = array(
array(3, 3),
array('a', 'a'),
array($date, $date),
array($object, $object),
array(null, 1),
);
if (PHP_VERSION_ID >= 50500) {
$immutableDate = new \DateTimeImmutable('2000-01-01');
$comparisons[] = array($immutableDate, $immutableDate);
}
return $comparisons;
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(1, '1', 2, '2', 'integer'),
array(2, '2', '2', '"2"', 'string'),
array('22', '"22"', '333', '"333"', 'string'),
array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', 'DateTime'),
array(new \DateTime('2001-01-01'), 'Jan 1, 2001, 12:00 AM', new \DateTime('1999-01-01'), 'Jan 1, 1999, 12:00 AM', 'DateTime'),
array(new ComparisonTest_Class(4), '4', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
);
}
}

View file

@ -1,332 +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\Image;
use Symfony\Component\Validator\Constraints\ImageValidator;
use Symfony\Component\Validator\Validation;
/**
* @requires extension fileinfo
*/
class ImageValidatorTest extends AbstractConstraintValidatorTest
{
protected $context;
/**
* @var ImageValidator
*/
protected $validator;
protected $path;
protected $image;
protected $imageLandscape;
protected $imagePortrait;
protected $image4By3;
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new ImageValidator();
}
protected function setUp()
{
parent::setUp();
$this->image = __DIR__.'/Fixtures/test.gif';
$this->imageLandscape = __DIR__.'/Fixtures/test_landscape.gif';
$this->imagePortrait = __DIR__.'/Fixtures/test_portrait.gif';
$this->image4By3 = __DIR__.'/Fixtures/test_4by3.gif';
}
public function testNullIsValid()
{
$this->validator->validate(null, new Image());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Image());
$this->assertNoViolation();
}
public function testValidImage()
{
$this->validator->validate($this->image, new Image());
$this->assertNoViolation();
}
public function testFileNotFound()
{
// Check that the logic from FileValidator still works
$constraint = new Image(array(
'notFoundMessage' => 'myMessage',
));
$this->validator->validate('foobar', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ file }}', '"foobar"')
->setCode(Image::NOT_FOUND_ERROR)
->assertRaised();
}
public function testValidSize()
{
$constraint = new Image(array(
'minWidth' => 1,
'maxWidth' => 2,
'minHeight' => 1,
'maxHeight' => 2,
));
$this->validator->validate($this->image, $constraint);
$this->assertNoViolation();
}
public function testWidthTooSmall()
{
$constraint = new Image(array(
'minWidth' => 3,
'minWidthMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ width }}', '2')
->setParameter('{{ min_width }}', '3')
->setCode(Image::TOO_NARROW_ERROR)
->assertRaised();
}
public function testWidthTooBig()
{
$constraint = new Image(array(
'maxWidth' => 1,
'maxWidthMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ width }}', '2')
->setParameter('{{ max_width }}', '1')
->setCode(Image::TOO_WIDE_ERROR)
->assertRaised();
}
public function testHeightTooSmall()
{
$constraint = new Image(array(
'minHeight' => 3,
'minHeightMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ height }}', '2')
->setParameter('{{ min_height }}', '3')
->setCode(Image::TOO_LOW_ERROR)
->assertRaised();
}
public function testHeightTooBig()
{
$constraint = new Image(array(
'maxHeight' => 1,
'maxHeightMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ height }}', '2')
->setParameter('{{ max_height }}', '1')
->setCode(Image::TOO_HIGH_ERROR)
->assertRaised();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMinWidth()
{
$constraint = new Image(array(
'minWidth' => '1abc',
));
$this->validator->validate($this->image, $constraint);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMaxWidth()
{
$constraint = new Image(array(
'maxWidth' => '1abc',
));
$this->validator->validate($this->image, $constraint);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMinHeight()
{
$constraint = new Image(array(
'minHeight' => '1abc',
));
$this->validator->validate($this->image, $constraint);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMaxHeight()
{
$constraint = new Image(array(
'maxHeight' => '1abc',
));
$this->validator->validate($this->image, $constraint);
}
public function testRatioTooSmall()
{
$constraint = new Image(array(
'minRatio' => 2,
'minRatioMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ ratio }}', 1)
->setParameter('{{ min_ratio }}', 2)
->setCode(Image::RATIO_TOO_SMALL_ERROR)
->assertRaised();
}
public function testRatioTooBig()
{
$constraint = new Image(array(
'maxRatio' => 0.5,
'maxRatioMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ ratio }}', 1)
->setParameter('{{ max_ratio }}', 0.5)
->setCode(Image::RATIO_TOO_BIG_ERROR)
->assertRaised();
}
public function testMaxRatioUsesTwoDecimalsOnly()
{
$constraint = new Image(array(
'maxRatio' => 1.33,
));
$this->validator->validate($this->image4By3, $constraint);
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMinRatio()
{
$constraint = new Image(array(
'minRatio' => '1abc',
));
$this->validator->validate($this->image, $constraint);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidMaxRatio()
{
$constraint = new Image(array(
'maxRatio' => '1abc',
));
$this->validator->validate($this->image, $constraint);
}
public function testSquareNotAllowed()
{
$constraint = new Image(array(
'allowSquare' => false,
'allowSquareMessage' => 'myMessage',
));
$this->validator->validate($this->image, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ width }}', 2)
->setParameter('{{ height }}', 2)
->setCode(Image::SQUARE_NOT_ALLOWED_ERROR)
->assertRaised();
}
public function testLandscapeNotAllowed()
{
$constraint = new Image(array(
'allowLandscape' => false,
'allowLandscapeMessage' => 'myMessage',
));
$this->validator->validate($this->imageLandscape, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ width }}', 2)
->setParameter('{{ height }}', 1)
->setCode(Image::LANDSCAPE_NOT_ALLOWED_ERROR)
->assertRaised();
}
public function testPortraitNotAllowed()
{
$constraint = new Image(array(
'allowPortrait' => false,
'allowPortraitMessage' => 'myMessage',
));
$this->validator->validate($this->imagePortrait, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ width }}', 1)
->setParameter('{{ height }}', 2)
->setCode(Image::PORTRAIT_NOT_ALLOWED_ERROR)
->assertRaised();
}
}

View file

@ -1,444 +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\Ip;
use Symfony\Component\Validator\Constraints\IpValidator;
use Symfony\Component\Validator\Validation;
class IpValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IpValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Ip());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Ip());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Ip());
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testInvalidValidatorVersion()
{
new Ip(array(
'version' => 666,
));
}
/**
* @dataProvider getValidIpsV4
*/
public function testValidIpsV4($ip)
{
$this->validator->validate($ip, new Ip(array(
'version' => Ip::V4,
)));
$this->assertNoViolation();
}
public function getValidIpsV4()
{
return array(
array('0.0.0.0'),
array('10.0.0.0'),
array('123.45.67.178'),
array('172.16.0.0'),
array('192.168.1.0'),
array('224.0.0.1'),
array('255.255.255.255'),
array('127.0.0.0'),
);
}
/**
* @dataProvider getValidIpsV6
*/
public function testValidIpsV6($ip)
{
$this->validator->validate($ip, new Ip(array(
'version' => Ip::V6,
)));
$this->assertNoViolation();
}
public function getValidIpsV6()
{
return array(
array('2001:0db8:85a3:0000:0000:8a2e:0370:7334'),
array('2001:0DB8:85A3:0000:0000:8A2E:0370:7334'),
array('2001:0Db8:85a3:0000:0000:8A2e:0370:7334'),
array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
array('fe80:0000:0000:0000:0202:b3ff:fe1e:8329'),
array('fe80:0:0:0:202:b3ff:fe1e:8329'),
array('fe80::202:b3ff:fe1e:8329'),
array('0:0:0:0:0:0:0:0'),
array('::'),
array('0::'),
array('::0'),
array('0::0'),
// IPv4 mapped to IPv6
array('2001:0db8:85a3:0000:0000:8a2e:0.0.0.0'),
array('::0.0.0.0'),
array('::255.255.255.255'),
array('::123.45.67.178'),
);
}
/**
* @dataProvider getValidIpsAll
*/
public function testValidIpsAll($ip)
{
$this->validator->validate($ip, new Ip(array(
'version' => Ip::ALL,
)));
$this->assertNoViolation();
}
public function getValidIpsAll()
{
return array_merge($this->getValidIpsV4(), $this->getValidIpsV6());
}
/**
* @dataProvider getInvalidIpsV4
*/
public function testInvalidIpsV4($ip)
{
$constraint = new Ip(array(
'version' => Ip::V4,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidIpsV4()
{
return array(
array('0'),
array('0.0'),
array('0.0.0'),
array('256.0.0.0'),
array('0.256.0.0'),
array('0.0.256.0'),
array('0.0.0.256'),
array('-1.0.0.0'),
array('foobar'),
);
}
/**
* @dataProvider getInvalidPrivateIpsV4
*/
public function testInvalidPrivateIpsV4($ip)
{
$constraint = new Ip(array(
'version' => Ip::V4_NO_PRIV,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidPrivateIpsV4()
{
return array(
array('10.0.0.0'),
array('172.16.0.0'),
array('192.168.1.0'),
);
}
/**
* @dataProvider getInvalidReservedIpsV4
*/
public function testInvalidReservedIpsV4($ip)
{
$constraint = new Ip(array(
'version' => Ip::V4_NO_RES,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidReservedIpsV4()
{
return array(
array('0.0.0.0'),
array('224.0.0.1'),
array('255.255.255.255'),
);
}
/**
* @dataProvider getInvalidPublicIpsV4
*/
public function testInvalidPublicIpsV4($ip)
{
$constraint = new Ip(array(
'version' => Ip::V4_ONLY_PUBLIC,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidPublicIpsV4()
{
return array_merge($this->getInvalidPrivateIpsV4(), $this->getInvalidReservedIpsV4());
}
/**
* @dataProvider getInvalidIpsV6
*/
public function testInvalidIpsV6($ip)
{
$constraint = new Ip(array(
'version' => Ip::V6,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidIpsV6()
{
return array(
array('z001:0db8:85a3:0000:0000:8a2e:0370:7334'),
array('fe80'),
array('fe80:8329'),
array('fe80:::202:b3ff:fe1e:8329'),
array('fe80::202:b3ff::fe1e:8329'),
// IPv4 mapped to IPv6
array('2001:0db8:85a3:0000:0000:8a2e:0370:0.0.0.0'),
array('::0.0'),
array('::0.0.0'),
array('::256.0.0.0'),
array('::0.256.0.0'),
array('::0.0.256.0'),
array('::0.0.0.256'),
);
}
/**
* @dataProvider getInvalidPrivateIpsV6
*/
public function testInvalidPrivateIpsV6($ip)
{
$constraint = new Ip(array(
'version' => Ip::V6_NO_PRIV,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidPrivateIpsV6()
{
return array(
array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
);
}
/**
* @dataProvider getInvalidReservedIpsV6
*/
public function testInvalidReservedIpsV6($ip)
{
$constraint = new Ip(array(
'version' => Ip::V6_NO_RES,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidReservedIpsV6()
{
// Quoting after official filter documentation:
// "FILTER_FLAG_NO_RES_RANGE = This flag does not apply to IPv6 addresses."
// Full description: http://php.net/manual/en/filter.filters.flags.php
return $this->getInvalidIpsV6();
}
/**
* @dataProvider getInvalidPublicIpsV6
*/
public function testInvalidPublicIpsV6($ip)
{
$constraint = new Ip(array(
'version' => Ip::V6_ONLY_PUBLIC,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidPublicIpsV6()
{
return array_merge($this->getInvalidPrivateIpsV6(), $this->getInvalidReservedIpsV6());
}
/**
* @dataProvider getInvalidIpsAll
*/
public function testInvalidIpsAll($ip)
{
$constraint = new Ip(array(
'version' => Ip::ALL,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidIpsAll()
{
return array_merge($this->getInvalidIpsV4(), $this->getInvalidIpsV6());
}
/**
* @dataProvider getInvalidPrivateIpsAll
*/
public function testInvalidPrivateIpsAll($ip)
{
$constraint = new Ip(array(
'version' => Ip::ALL_NO_PRIV,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidPrivateIpsAll()
{
return array_merge($this->getInvalidPrivateIpsV4(), $this->getInvalidPrivateIpsV6());
}
/**
* @dataProvider getInvalidReservedIpsAll
*/
public function testInvalidReservedIpsAll($ip)
{
$constraint = new Ip(array(
'version' => Ip::ALL_NO_RES,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidReservedIpsAll()
{
return array_merge($this->getInvalidReservedIpsV4(), $this->getInvalidReservedIpsV6());
}
/**
* @dataProvider getInvalidPublicIpsAll
*/
public function testInvalidPublicIpsAll($ip)
{
$constraint = new Ip(array(
'version' => Ip::ALL_ONLY_PUBLIC,
'message' => 'myMessage',
));
$this->validator->validate($ip, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$ip.'"')
->assertRaised();
}
public function getInvalidPublicIpsAll()
{
return array_merge($this->getInvalidPublicIpsV4(), $this->getInvalidPublicIpsV6());
}
}

View file

@ -1,56 +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\IsFalse;
use Symfony\Component\Validator\Constraints\IsFalseValidator;
use Symfony\Component\Validator\Validation;
class IsFalseValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IsFalseValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new IsFalse());
$this->assertNoViolation();
}
public function testFalseIsValid()
{
$this->validator->validate(false, new IsFalse());
$this->assertNoViolation();
}
public function testTrueIsInvalid()
{
$constraint = new IsFalse(array(
'message' => 'myMessage',
));
$this->validator->validate(true, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'true')
->assertRaised();
}
}

View file

@ -1,66 +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\IsNull;
use Symfony\Component\Validator\Constraints\IsNullValidator;
use Symfony\Component\Validator\Validation;
class IsNullValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IsNullValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new IsNull());
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value, $valueAsString)
{
$constraint = new IsNull(array(
'message' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $valueAsString)
->assertRaised();
}
public function getInvalidValues()
{
return array(
array(0, '0'),
array(false, 'false'),
array(true, 'true'),
array('', '""'),
array('foo bar', '"foo bar"'),
array(new \DateTime(), 'object'),
array(new \stdClass(), 'object'),
array(array(), 'array'),
);
}
}

View file

@ -1,56 +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\IsTrue;
use Symfony\Component\Validator\Constraints\IsTrueValidator;
use Symfony\Component\Validator\Validation;
class IsTrueValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IsTrueValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new IsTrue());
$this->assertNoViolation();
}
public function testTrueIsValid()
{
$this->validator->validate(true, new IsTrue());
$this->assertNoViolation();
}
public function testFalseIsInvalid()
{
$constraint = new IsTrue(array(
'message' => 'myMessage',
));
$this->validator->validate(false, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'false')
->assertRaised();
}
}

View file

@ -1,271 +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\Isbn;
use Symfony\Component\Validator\Constraints\IsbnValidator;
use Symfony\Component\Validator\Validation;
/**
* @see https://en.wikipedia.org/wiki/Isbn
*/
class IsbnValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IsbnValidator();
}
public function getValidIsbn10()
{
return array(
array('2723442284'),
array('2723442276'),
array('2723455041'),
array('2070546810'),
array('2711858839'),
array('2756406767'),
array('2870971648'),
array('226623854X'),
array('2851806424'),
array('0321812700'),
array('0-45122-5244'),
array('0-4712-92311'),
array('0-9752298-0-X'),
);
}
public function getInvalidIsbn10()
{
return array(
array('27234422841', Isbn::TOO_LONG_ERROR),
array('272344228', Isbn::TOO_SHORT_ERROR),
array('0-4712-9231', Isbn::TOO_SHORT_ERROR),
array('1234567890', Isbn::CHECKSUM_FAILED_ERROR),
array('0987656789', Isbn::CHECKSUM_FAILED_ERROR),
array('7-35622-5444', Isbn::CHECKSUM_FAILED_ERROR),
array('0-4X19-92611', Isbn::CHECKSUM_FAILED_ERROR),
array('0_45122_5244', Isbn::INVALID_CHARACTERS_ERROR),
array('2870#971#648', Isbn::INVALID_CHARACTERS_ERROR),
array('0-9752298-0-x', Isbn::INVALID_CHARACTERS_ERROR),
array('1A34567890', Isbn::INVALID_CHARACTERS_ERROR),
// chr(1) evaluates to 0
// 2070546810 is valid
array('2'.chr(1).'70546810', Isbn::INVALID_CHARACTERS_ERROR),
);
}
public function getValidIsbn13()
{
return array(
array('978-2723442282'),
array('978-2723442275'),
array('978-2723455046'),
array('978-2070546817'),
array('978-2711858835'),
array('978-2756406763'),
array('978-2870971642'),
array('978-2266238540'),
array('978-2851806420'),
array('978-0321812704'),
array('978-0451225245'),
array('978-0471292319'),
);
}
public function getInvalidIsbn13()
{
return array(
array('978-27234422821', Isbn::TOO_LONG_ERROR),
array('978-272344228', Isbn::TOO_SHORT_ERROR),
array('978-2723442-82', Isbn::TOO_SHORT_ERROR),
array('978-2723442281', Isbn::CHECKSUM_FAILED_ERROR),
array('978-0321513774', Isbn::CHECKSUM_FAILED_ERROR),
array('979-0431225385', Isbn::CHECKSUM_FAILED_ERROR),
array('980-0474292319', Isbn::CHECKSUM_FAILED_ERROR),
array('0-4X19-92619812', Isbn::INVALID_CHARACTERS_ERROR),
array('978_2723442282', Isbn::INVALID_CHARACTERS_ERROR),
array('978#2723442282', Isbn::INVALID_CHARACTERS_ERROR),
array('978-272C442282', Isbn::INVALID_CHARACTERS_ERROR),
// chr(1) evaluates to 0
// 978-2070546817 is valid
array('978-2'.chr(1).'70546817', Isbn::INVALID_CHARACTERS_ERROR),
);
}
public function getValidIsbn()
{
return array_merge(
$this->getValidIsbn10(),
$this->getValidIsbn13()
);
}
public function getInvalidIsbn()
{
return array_merge(
$this->getInvalidIsbn10(),
$this->getInvalidIsbn13()
);
}
public function testNullIsValid()
{
$constraint = new Isbn(true);
$this->validator->validate(null, $constraint);
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$constraint = new Isbn(true);
$this->validator->validate('', $constraint);
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$constraint = new Isbn(true);
$this->validator->validate(new \stdClass(), $constraint);
}
/**
* @dataProvider getValidIsbn10
*/
public function testValidIsbn10($isbn)
{
$constraint = new Isbn(array(
'type' => 'isbn10',
));
$this->validator->validate($isbn, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidIsbn10
*/
public function testInvalidIsbn10($isbn, $code)
{
$constraint = new Isbn(array(
'type' => 'isbn10',
'isbn10Message' => 'myMessage',
));
$this->validator->validate($isbn, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$isbn.'"')
->setCode($code)
->assertRaised();
}
/**
* @dataProvider getValidIsbn13
*/
public function testValidIsbn13($isbn)
{
$constraint = new Isbn(array('type' => 'isbn13'));
$this->validator->validate($isbn, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidIsbn13
*/
public function testInvalidIsbn13($isbn, $code)
{
$constraint = new Isbn(array(
'type' => 'isbn13',
'isbn13Message' => 'myMessage',
));
$this->validator->validate($isbn, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$isbn.'"')
->setCode($code)
->assertRaised();
}
/**
* @dataProvider getValidIsbn
*/
public function testValidIsbnAny($isbn)
{
$constraint = new Isbn();
$this->validator->validate($isbn, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidIsbn10
*/
public function testInvalidIsbnAnyIsbn10($isbn, $code)
{
$constraint = new Isbn(array(
'bothIsbnMessage' => 'myMessage',
));
$this->validator->validate($isbn, $constraint);
// Too long for an ISBN-10, but not long enough for an ISBN-13
if (Isbn::TOO_LONG_ERROR === $code) {
$code = Isbn::TYPE_NOT_RECOGNIZED_ERROR;
}
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$isbn.'"')
->setCode($code)
->assertRaised();
}
/**
* @dataProvider getInvalidIsbn13
*/
public function testInvalidIsbnAnyIsbn13($isbn, $code)
{
$constraint = new Isbn(array(
'bothIsbnMessage' => 'myMessage',
));
$this->validator->validate($isbn, $constraint);
// Too short for an ISBN-13, but not short enough for an ISBN-10
if (Isbn::TOO_SHORT_ERROR === $code) {
$code = Isbn::TYPE_NOT_RECOGNIZED_ERROR;
}
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$isbn.'"')
->setCode($code)
->assertRaised();
}
}

View file

@ -1,187 +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\Issn;
use Symfony\Component\Validator\Constraints\IssnValidator;
use Symfony\Component\Validator\Validation;
/**
* @see https://en.wikipedia.org/wiki/Issn
*/
class IssnValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new IssnValidator();
}
public function getValidLowerCasedIssn()
{
return array(
array('2162-321x'),
array('2160-200x'),
array('1537-453x'),
array('1937-710x'),
array('0002-922x'),
array('1553-345x'),
array('1553-619x'),
);
}
public function getValidNonHyphenatedIssn()
{
return array(
array('2162321X'),
array('01896016'),
array('15744647'),
array('14350645'),
array('07174055'),
array('20905076'),
array('14401592'),
);
}
public function getFullValidIssn()
{
return array(
array('1550-7416'),
array('1539-8560'),
array('2156-5376'),
array('1119-023X'),
array('1684-5315'),
array('1996-0786'),
array('1684-5374'),
array('1996-0794'),
);
}
public function getValidIssn()
{
return array_merge(
$this->getValidLowerCasedIssn(),
$this->getValidNonHyphenatedIssn(),
$this->getFullValidIssn()
);
}
public function getInvalidIssn()
{
return array(
array(0, Issn::TOO_SHORT_ERROR),
array('1539', Issn::TOO_SHORT_ERROR),
array('2156-537A', Issn::INVALID_CHARACTERS_ERROR),
array('1119-0231', Issn::CHECKSUM_FAILED_ERROR),
array('1684-5312', Issn::CHECKSUM_FAILED_ERROR),
array('1996-0783', Issn::CHECKSUM_FAILED_ERROR),
array('1684-537X', Issn::CHECKSUM_FAILED_ERROR),
array('1996-0795', Issn::CHECKSUM_FAILED_ERROR),
);
}
public function testNullIsValid()
{
$constraint = new Issn();
$this->validator->validate(null, $constraint);
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$constraint = new Issn();
$this->validator->validate('', $constraint);
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$constraint = new Issn();
$this->validator->validate(new \stdClass(), $constraint);
}
/**
* @dataProvider getValidLowerCasedIssn
*/
public function testCaseSensitiveIssns($issn)
{
$constraint = new Issn(array(
'caseSensitive' => true,
'message' => 'myMessage',
));
$this->validator->validate($issn, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$issn.'"')
->setCode(Issn::INVALID_CASE_ERROR)
->assertRaised();
}
/**
* @dataProvider getValidNonHyphenatedIssn
*/
public function testRequireHyphenIssns($issn)
{
$constraint = new Issn(array(
'requireHyphen' => true,
'message' => 'myMessage',
));
$this->validator->validate($issn, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$issn.'"')
->setCode(Issn::MISSING_HYPHEN_ERROR)
->assertRaised();
}
/**
* @dataProvider getValidIssn
*/
public function testValidIssn($issn)
{
$constraint = new Issn();
$this->validator->validate($issn, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getInvalidIssn
*/
public function testInvalidIssn($issn, $code)
{
$constraint = new Issn(array(
'message' => 'myMessage',
));
$this->validator->validate($issn, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$issn.'"')
->setCode($code)
->assertRaised();
}
}

View file

@ -1,109 +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\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Language;
use Symfony\Component\Validator\Constraints\LanguageValidator;
use Symfony\Component\Validator\Validation;
class LanguageValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new LanguageValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Language());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Language());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Language());
}
/**
* @dataProvider getValidLanguages
*/
public function testValidLanguages($language)
{
$this->validator->validate($language, new Language());
$this->assertNoViolation();
}
public function getValidLanguages()
{
return array(
array('en'),
array('en_US'),
array('my'),
);
}
/**
* @dataProvider getInvalidLanguages
*/
public function testInvalidLanguages($language)
{
$constraint = new Language(array(
'message' => 'myMessage',
));
$this->validator->validate($language, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$language.'"')
->assertRaised();
}
public function getInvalidLanguages()
{
return array(
array('EN'),
array('foobar'),
);
}
public function testValidateUsingCountrySpecificLocale()
{
IntlTestHelper::requireFullIntl($this);
\Locale::setDefault('fr_FR');
$existingLanguage = 'en';
$this->validator->validate($existingLanguage, new Language(array(
'message' => 'aMessage',
)));
$this->assertNoViolation();
}
}

View file

@ -1,255 +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\Length;
use Symfony\Component\Validator\Constraints\LengthValidator;
use Symfony\Component\Validator\Validation;
class LengthValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new LengthValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Length(6));
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Length(6));
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Length(5));
}
public function getThreeOrLessCharacters()
{
return array(
array(12),
array('12'),
array('üü'),
array('éé'),
array(123),
array('123'),
array('üüü'),
array('ééé'),
);
}
public function getFourCharacters()
{
return array(
array(1234),
array('1234'),
array('üüüü'),
array('éééé'),
);
}
public function getFiveOrMoreCharacters()
{
return array(
array(12345),
array('12345'),
array('üüüüü'),
array('ééééé'),
array(123456),
array('123456'),
array('üüüüüü'),
array('éééééé'),
);
}
public function getOneCharset()
{
if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) {
$this->markTestSkipped('Mbstring or iconv is required for this test.');
}
return array(
array('é', 'utf8', true),
array("\xE9", 'CP1252', true),
array("\xE9", 'XXX', false),
array("\xE9", 'utf8', false),
);
}
/**
* @dataProvider getFiveOrMoreCharacters
*/
public function testValidValuesMin($value)
{
$constraint = new Length(array('min' => 5));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getThreeOrLessCharacters
*/
public function testValidValuesMax($value)
{
$constraint = new Length(array('max' => 3));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getFourCharacters
*/
public function testValidValuesExact($value)
{
$constraint = new Length(4);
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getThreeOrLessCharacters
*/
public function testInvalidValuesMin($value)
{
$constraint = new Length(array(
'min' => 4,
'minMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Length::TOO_SHORT_ERROR)
->assertRaised();
}
/**
* @dataProvider getFiveOrMoreCharacters
*/
public function testInvalidValuesMax($value)
{
$constraint = new Length(array(
'max' => 4,
'maxMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Length::TOO_LONG_ERROR)
->assertRaised();
}
/**
* @dataProvider getThreeOrLessCharacters
*/
public function testInvalidValuesExactLessThanFour($value)
{
$constraint = new Length(array(
'min' => 4,
'max' => 4,
'exactMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Length::TOO_SHORT_ERROR)
->assertRaised();
}
/**
* @dataProvider getFiveOrMoreCharacters
*/
public function testInvalidValuesExactMoreThanFour($value)
{
$constraint = new Length(array(
'min' => 4,
'max' => 4,
'exactMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->setParameter('{{ limit }}', 4)
->setInvalidValue($value)
->setPlural(4)
->setCode(Length::TOO_LONG_ERROR)
->assertRaised();
}
/**
* @dataProvider getOneCharset
*/
public function testOneCharset($value, $charset, $isValid)
{
$constraint = new Length(array(
'min' => 1,
'max' => 1,
'charset' => $charset,
'charsetMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
if ($isValid) {
$this->assertNoViolation();
} else {
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->setParameter('{{ charset }}', $charset)
->setInvalidValue($value)
->assertRaised();
}
}
public function testConstraintGetDefaultOption()
{
$constraint = new Length(5);
$this->assertEquals(5, $constraint->min);
$this->assertEquals(5, $constraint->max);
}
}

View file

@ -1,74 +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\LessThanOrEqual;
use Symfony\Component\Validator\Constraints\LessThanOrEqualValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class LessThanOrEqualValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new LessThanOrEqualValidator();
}
protected function createConstraint(array $options)
{
return new LessThanOrEqual($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(1, 2),
array(1, 1),
array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
array(new \DateTime('2000-01-01'), new \DateTime('2020-01-01')),
array(new \DateTime('2000-01-01'), '2000-01-01'),
array(new \DateTime('2000-01-01'), '2020-01-01'),
array(new \DateTime('2000-01-01 UTC'), '2000-01-01 UTC'),
array(new \DateTime('2000-01-01 UTC'), '2020-01-01 UTC'),
array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)),
array(new ComparisonTest_Class(5), new ComparisonTest_Class(5)),
array('a', 'a'),
array('a', 'z'),
array(null, 1),
);
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(2, '2', 1, '1', 'integer'),
array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2010-01-01 UTC'), 'Jan 1, 2010, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(4), '4', __NAMESPACE__.'\ComparisonTest_Class'),
array('c', '"c"', 'b', '"b"', 'string'),
);
}
}

View file

@ -1,73 +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\LessThan;
use Symfony\Component\Validator\Constraints\LessThanValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class LessThanValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new LessThanValidator();
}
protected function createConstraint(array $options)
{
return new LessThan($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(1, 2),
array(new \DateTime('2000-01-01'), new \DateTime('2010-01-01')),
array(new \DateTime('2000-01-01'), '2010-01-01'),
array(new \DateTime('2000-01-01 UTC'), '2010-01-01 UTC'),
array(new ComparisonTest_Class(4), new ComparisonTest_Class(5)),
array('22', '333'),
array(null, 1),
);
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(3, '3', 2, '2', 'integer'),
array(2, '2', 2, '2', 'integer'),
array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2010-01-01'), 'Jan 1, 2010, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2010-01-01 UTC'), 'Jan 1, 2010, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000-01-01 UTC'), 'Jan 1, 2000, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
array(new ComparisonTest_Class(6), '6', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
array('333', '"333"', '22', '"22"', 'string'),
);
}
}

View file

@ -1,96 +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\Locale;
use Symfony\Component\Validator\Constraints\LocaleValidator;
use Symfony\Component\Validator\Validation;
class LocaleValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new LocaleValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Locale());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Locale());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Locale());
}
/**
* @dataProvider getValidLocales
*/
public function testValidLocales($locale)
{
$this->validator->validate($locale, new Locale());
$this->assertNoViolation();
}
public function getValidLocales()
{
return array(
array('en'),
array('en_US'),
array('pt'),
array('pt_PT'),
array('zh_Hans'),
);
}
/**
* @dataProvider getInvalidLocales
*/
public function testInvalidLocales($locale)
{
$constraint = new Locale(array(
'message' => 'myMessage',
));
$this->validator->validate($locale, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$locale.'"')
->assertRaised();
}
public function getInvalidLocales()
{
return array(
array('EN'),
array('foobar'),
);
}
}

View file

@ -1,127 +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\Luhn;
use Symfony\Component\Validator\Constraints\LuhnValidator;
use Symfony\Component\Validator\Validation;
class LuhnValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new LuhnValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Luhn());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Luhn());
$this->assertNoViolation();
}
/**
* @dataProvider getValidNumbers
*/
public function testValidNumbers($number)
{
$this->validator->validate($number, new Luhn());
$this->assertNoViolation();
}
public function getValidNumbers()
{
return array(
array('42424242424242424242'),
array('378282246310005'),
array('371449635398431'),
array('378734493671000'),
array('5610591081018250'),
array('30569309025904'),
array('38520000023237'),
array('6011111111111117'),
array('6011000990139424'),
array('3530111333300000'),
array('3566002020360505'),
array('5555555555554444'),
array('5105105105105100'),
array('4111111111111111'),
array('4012888888881881'),
array('4222222222222'),
array('5019717010103742'),
array('6331101999990016'),
);
}
/**
* @dataProvider getInvalidNumbers
*/
public function testInvalidNumbers($number, $code)
{
$constraint = new Luhn(array(
'message' => 'myMessage',
));
$this->validator->validate($number, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$number.'"')
->setCode($code)
->assertRaised();
}
public function getInvalidNumbers()
{
return array(
array('1234567812345678', Luhn::CHECKSUM_FAILED_ERROR),
array('4222222222222222', Luhn::CHECKSUM_FAILED_ERROR),
array('0000000000000000', Luhn::CHECKSUM_FAILED_ERROR),
array('000000!000000000', Luhn::INVALID_CHARACTERS_ERROR),
array('42-22222222222222', Luhn::INVALID_CHARACTERS_ERROR),
);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
* @dataProvider getInvalidTypes
*/
public function testInvalidTypes($number)
{
$constraint = new Luhn();
$this->validator->validate($number, $constraint);
}
public function getInvalidTypes()
{
return array(
array(0),
array(123),
array(42424242424242424242),
array(378282246310005),
array(371449635398431),
);
}
}

View file

@ -1,102 +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\NotBlank;
use Symfony\Component\Validator\Constraints\NotBlankValidator;
use Symfony\Component\Validator\Validation;
class NotBlankValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new NotBlankValidator();
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value)
{
$this->validator->validate($value, new NotBlank());
$this->assertNoViolation();
}
public function getValidValues()
{
return array(
array('foobar'),
array(0),
array(0.0),
array('0'),
array(1234),
);
}
public function testNullIsInvalid()
{
$constraint = new NotBlank(array(
'message' => 'myMessage',
));
$this->validator->validate(null, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'null')
->assertRaised();
}
public function testBlankIsInvalid()
{
$constraint = new NotBlank(array(
'message' => 'myMessage',
));
$this->validator->validate('', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '""')
->assertRaised();
}
public function testFalseIsInvalid()
{
$constraint = new NotBlank(array(
'message' => 'myMessage',
));
$this->validator->validate(false, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'false')
->assertRaised();
}
public function testEmptyArrayIsInvalid()
{
$constraint = new NotBlank(array(
'message' => 'myMessage',
));
$this->validator->validate(array(), $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', 'array')
->assertRaised();
}
}

View file

@ -1,69 +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\NotEqualTo;
use Symfony\Component\Validator\Constraints\NotEqualToValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class NotEqualToValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new NotEqualToValidator();
}
protected function createConstraint(array $options)
{
return new NotEqualTo($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(1, 2),
array('22', '333'),
array(new \DateTime('2001-01-01'), new \DateTime('2000-01-01')),
array(new \DateTime('2001-01-01'), '2000-01-01'),
array(new \DateTime('2001-01-01 UTC'), '2000-01-01 UTC'),
array(new ComparisonTest_Class(6), new ComparisonTest_Class(5)),
array(null, 1),
);
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
return array(
array(3, '3', 3, '3', 'integer'),
array('2', '"2"', 2, '2', 'integer'),
array('a', '"a"', 'a', '"a"', 'string'),
array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000-01-01'), 'Jan 1, 2000, 12:00 AM', '2000-01-01', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new \DateTime('2000-01-01 UTC'), 'Jan 1, 2000, 12:00 AM', '2000-01-01 UTC', 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array(new ComparisonTest_Class(5), '5', new ComparisonTest_Class(5), '5', __NAMESPACE__.'\ComparisonTest_Class'),
);
}
}

View file

@ -1,87 +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\NotIdenticalTo;
use Symfony\Component\Validator\Constraints\NotIdenticalToValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Daniel Holmes <daniel@danielholmes.org>
*/
class NotIdenticalToValidatorTest extends AbstractComparisonValidatorTestCase
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new NotIdenticalToValidator();
}
protected function createConstraint(array $options)
{
return new NotIdenticalTo($options);
}
/**
* {@inheritdoc}
*/
public function provideValidComparisons()
{
return array(
array(1, 2),
array('2', 2),
array('22', '333'),
array(new \DateTime('2001-01-01'), new \DateTime('2000-01-01')),
array(new \DateTime('2000-01-01'), new \DateTime('2000-01-01')),
array(new \DateTime('2001-01-01'), '2000-01-01'),
array(new \DateTime('2000-01-01'), '2000-01-01'),
array(new \DateTime('2001-01-01'), '2000-01-01'),
array(new \DateTime('2000-01-01 UTC'), '2000-01-01 UTC'),
array(null, 1),
);
}
public function provideAllInvalidComparisons()
{
$this->setDefaultTimezone('UTC');
// Don't call addPhp5Dot5Comparisons() automatically, as it does
// not take care of identical objects
$comparisons = $this->provideInvalidComparisons();
$this->restoreDefaultTimezone();
return $comparisons;
}
/**
* {@inheritdoc}
*/
public function provideInvalidComparisons()
{
$date = new \DateTime('2000-01-01');
$object = new ComparisonTest_Class(2);
$comparisons = array(
array(3, '3', 3, '3', 'integer'),
array('a', '"a"', 'a', '"a"', 'string'),
array($date, 'Jan 1, 2000, 12:00 AM', $date, 'Jan 1, 2000, 12:00 AM', 'DateTime'),
array($object, '2', $object, '2', __NAMESPACE__.'\ComparisonTest_Class'),
);
return $comparisons;
}
}

View file

@ -1,60 +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\NotNull;
use Symfony\Component\Validator\Constraints\NotNullValidator;
use Symfony\Component\Validator\Validation;
class NotNullValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new NotNullValidator();
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value)
{
$this->validator->validate($value, new NotNull());
$this->assertNoViolation();
}
public function getValidValues()
{
return array(
array(0),
array(false),
array(true),
array(''),
);
}
public function testNullIsInvalid()
{
$constraint = new NotNull(array(
'message' => 'myMessage',
));
$this->validator->validate(null, $constraint);
$this->buildViolation('myMessage')->assertRaised();
}
}

View file

@ -1,403 +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\Intl\Util\IntlTestHelper;
use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\RangeValidator;
use Symfony\Component\Validator\Validation;
class RangeValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new RangeValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Range(array('min' => 10, 'max' => 20)));
$this->assertNoViolation();
}
public function getTenToTwenty()
{
return array(
array(10.00001),
array(19.99999),
array('10.00001'),
array('19.99999'),
array(10),
array(20),
array(10.0),
array(20.0),
);
}
public function getLessThanTen()
{
return array(
array(9.99999, '9.99999'),
array('9.99999', '"9.99999"'),
array(5, '5'),
array(1.0, '1.0'),
);
}
public function getMoreThanTwenty()
{
return array(
array(20.000001, '20.000001'),
array('20.000001', '"20.000001"'),
array(21, '21'),
array(30.0, '30.0'),
);
}
/**
* @dataProvider getTenToTwenty
*/
public function testValidValuesMin($value)
{
$constraint = new Range(array('min' => 10));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getTenToTwenty
*/
public function testValidValuesMax($value)
{
$constraint = new Range(array('max' => 20));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getTenToTwenty
*/
public function testValidValuesMinMax($value)
{
$constraint = new Range(array('min' => 10, 'max' => 20));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getLessThanTen
*/
public function testInvalidValuesMin($value, $formattedValue)
{
$constraint = new Range(array(
'min' => 10,
'minMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $formattedValue)
->setParameter('{{ limit }}', 10)
->setCode(Range::BELOW_RANGE_ERROR)
->assertRaised();
}
/**
* @dataProvider getMoreThanTwenty
*/
public function testInvalidValuesMax($value, $formattedValue)
{
$constraint = new Range(array(
'max' => 20,
'maxMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $formattedValue)
->setParameter('{{ limit }}', 20)
->setCode(Range::BEYOND_RANGE_ERROR)
->assertRaised();
}
/**
* @dataProvider getMoreThanTwenty
*/
public function testInvalidValuesCombinedMax($value, $formattedValue)
{
$constraint = new Range(array(
'min' => 10,
'max' => 20,
'minMessage' => 'myMinMessage',
'maxMessage' => 'myMaxMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMaxMessage')
->setParameter('{{ value }}', $formattedValue)
->setParameter('{{ limit }}', 20)
->setCode(Range::BEYOND_RANGE_ERROR)
->assertRaised();
}
/**
* @dataProvider getLessThanTen
*/
public function testInvalidValuesCombinedMin($value, $formattedValue)
{
$constraint = new Range(array(
'min' => 10,
'max' => 20,
'minMessage' => 'myMinMessage',
'maxMessage' => 'myMaxMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMinMessage')
->setParameter('{{ value }}', $formattedValue)
->setParameter('{{ limit }}', 10)
->setCode(Range::BELOW_RANGE_ERROR)
->assertRaised();
}
public function getTenthToTwentiethMarch2014()
{
// The provider runs before setUp(), so we need to manually fix
// the default timezone
$this->setDefaultTimezone('UTC');
$tests = array(
array(new \DateTime('March 10, 2014')),
array(new \DateTime('March 15, 2014')),
array(new \DateTime('March 20, 2014')),
);
if (PHP_VERSION_ID >= 50500) {
$tests[] = array(new \DateTimeImmutable('March 10, 2014'));
$tests[] = array(new \DateTimeImmutable('March 15, 2014'));
$tests[] = array(new \DateTimeImmutable('March 20, 2014'));
}
$this->restoreDefaultTimezone();
return $tests;
}
public function getSoonerThanTenthMarch2014()
{
// The provider runs before setUp(), so we need to manually fix
// the default timezone
$this->setDefaultTimezone('UTC');
$tests = array(
array(new \DateTime('March 20, 2013'), 'Mar 20, 2013, 12:00 AM'),
array(new \DateTime('March 9, 2014'), 'Mar 9, 2014, 12:00 AM'),
);
if (PHP_VERSION_ID >= 50500) {
$tests[] = array(new \DateTimeImmutable('March 20, 2013'), 'Mar 20, 2013, 12:00 AM');
$tests[] = array(new \DateTimeImmutable('March 9, 2014'), 'Mar 9, 2014, 12:00 AM');
}
$this->restoreDefaultTimezone();
return $tests;
}
public function getLaterThanTwentiethMarch2014()
{
// The provider runs before setUp(), so we need to manually fix
// the default timezone
$this->setDefaultTimezone('UTC');
$tests = array(
array(new \DateTime('March 21, 2014'), 'Mar 21, 2014, 12:00 AM'),
array(new \DateTime('March 9, 2015'), 'Mar 9, 2015, 12:00 AM'),
);
if (PHP_VERSION_ID >= 50500) {
$tests[] = array(new \DateTimeImmutable('March 21, 2014'), 'Mar 21, 2014, 12:00 AM');
$tests[] = array(new \DateTimeImmutable('March 9, 2015'), 'Mar 9, 2015, 12:00 AM');
}
$this->restoreDefaultTimezone();
return $tests;
}
/**
* @dataProvider getTenthToTwentiethMarch2014
*/
public function testValidDatesMin($value)
{
$constraint = new Range(array('min' => 'March 10, 2014'));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getTenthToTwentiethMarch2014
*/
public function testValidDatesMax($value)
{
$constraint = new Range(array('max' => 'March 20, 2014'));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getTenthToTwentiethMarch2014
*/
public function testValidDatesMinMax($value)
{
$constraint = new Range(array('min' => 'March 10, 2014', 'max' => 'March 20, 2014'));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
/**
* @dataProvider getSoonerThanTenthMarch2014
*/
public function testInvalidDatesMin($value, $dateTimeAsString)
{
// Conversion of dates to string differs between ICU versions
// Make sure we have the correct version loaded
IntlTestHelper::requireIntl($this);
$constraint = new Range(array(
'min' => 'March 10, 2014',
'minMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $dateTimeAsString)
->setParameter('{{ limit }}', 'Mar 10, 2014, 12:00 AM')
->setCode(Range::BELOW_RANGE_ERROR)
->assertRaised();
}
/**
* @dataProvider getLaterThanTwentiethMarch2014
*/
public function testInvalidDatesMax($value, $dateTimeAsString)
{
// Conversion of dates to string differs between ICU versions
// Make sure we have the correct version loaded
IntlTestHelper::requireIntl($this);
$constraint = new Range(array(
'max' => 'March 20, 2014',
'maxMessage' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $dateTimeAsString)
->setParameter('{{ limit }}', 'Mar 20, 2014, 12:00 AM')
->setCode(Range::BEYOND_RANGE_ERROR)
->assertRaised();
}
/**
* @dataProvider getLaterThanTwentiethMarch2014
*/
public function testInvalidDatesCombinedMax($value, $dateTimeAsString)
{
// Conversion of dates to string differs between ICU versions
// Make sure we have the correct version loaded
IntlTestHelper::requireIntl($this);
$constraint = new Range(array(
'min' => 'March 10, 2014',
'max' => 'March 20, 2014',
'minMessage' => 'myMinMessage',
'maxMessage' => 'myMaxMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMaxMessage')
->setParameter('{{ value }}', $dateTimeAsString)
->setParameter('{{ limit }}', 'Mar 20, 2014, 12:00 AM')
->setCode(Range::BEYOND_RANGE_ERROR)
->assertRaised();
}
/**
* @dataProvider getSoonerThanTenthMarch2014
*/
public function testInvalidDatesCombinedMin($value, $dateTimeAsString)
{
// Conversion of dates to string differs between ICU versions
// Make sure we have the correct version loaded
IntlTestHelper::requireIntl($this);
$constraint = new Range(array(
'min' => 'March 10, 2014',
'max' => 'March 20, 2014',
'minMessage' => 'myMinMessage',
'maxMessage' => 'myMaxMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMinMessage')
->setParameter('{{ value }}', $dateTimeAsString)
->setParameter('{{ limit }}', 'Mar 10, 2014, 12:00 AM')
->setCode(Range::BELOW_RANGE_ERROR)
->assertRaised();
}
public function getInvalidValues()
{
return array(
array(9.999999),
array(20.000001),
array('9.999999'),
array('20.000001'),
array(new \stdClass()),
);
}
public function testNonNumeric()
{
$this->validator->validate('abcd', new Range(array(
'min' => 10,
'max' => 20,
'invalidMessage' => 'myMessage',
)));
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"abcd"')
->setCode(Range::INVALID_VALUE_ERROR)
->assertRaised();
}
}

View file

@ -1,87 +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 Constraints;
use Symfony\Component\Validator\Constraints\Regex;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class RegexTest extends \PHPUnit_Framework_TestCase
{
public function testConstraintGetDefaultOption()
{
$constraint = new Regex('/^[0-9]+$/');
$this->assertSame('/^[0-9]+$/', $constraint->pattern);
}
public function provideHtmlPatterns()
{
return array(
// HTML5 wraps the pattern in ^(?:pattern)$
array('/^[0-9]+$/', '[0-9]+'),
array('/[0-9]+$/', '.*[0-9]+'),
array('/^[0-9]+/', '[0-9]+.*'),
array('/[0-9]+/', '.*[0-9]+.*'),
// We need a smart way to allow matching of patterns that contain
// ^ and $ at various sub-clauses of an or-clause
// .*(pattern).* seems to work correctly
array('/[0-9]$|[a-z]+/', '.*([0-9]$|[a-z]+).*'),
array('/[0-9]$|^[a-z]+/', '.*([0-9]$|^[a-z]+).*'),
array('/^[0-9]|[a-z]+$/', '.*(^[0-9]|[a-z]+$).*'),
// Unescape escaped delimiters
array('/^[0-9]+\/$/', '[0-9]+/'),
array('#^[0-9]+\#$#', '[0-9]+#'),
// Cannot be converted
array('/^[0-9]+$/i', null),
// Inverse matches are simple, just wrap in
// ((?!pattern).)*
array('/^[0-9]+$/', '((?!^[0-9]+$).)*', false),
array('/[0-9]+$/', '((?![0-9]+$).)*', false),
array('/^[0-9]+/', '((?!^[0-9]+).)*', false),
array('/[0-9]+/', '((?![0-9]+).)*', false),
array('/[0-9]$|[a-z]+/', '((?![0-9]$|[a-z]+).)*', false),
array('/[0-9]$|^[a-z]+/', '((?![0-9]$|^[a-z]+).)*', false),
array('/^[0-9]|[a-z]+$/', '((?!^[0-9]|[a-z]+$).)*', false),
array('/^[0-9]+\/$/', '((?!^[0-9]+/$).)*', false),
array('#^[0-9]+\#$#', '((?!^[0-9]+#$).)*', false),
array('/^[0-9]+$/i', null, false),
);
}
/**
* @dataProvider provideHtmlPatterns
*/
public function testGetHtmlPattern($pattern, $htmlPattern, $match = true)
{
$constraint = new Regex(array(
'pattern' => $pattern,
'match' => $match,
));
$this->assertSame($pattern, $constraint->pattern);
$this->assertSame($htmlPattern, $constraint->getHtmlPattern());
}
public function testGetCustomHtmlPattern()
{
$constraint = new Regex(array(
'pattern' => '((?![0-9]$|[a-z]+).)*',
'htmlPattern' => 'foobar',
));
$this->assertSame('((?![0-9]$|[a-z]+).)*', $constraint->pattern);
$this->assertSame('foobar', $constraint->getHtmlPattern());
}
}

View file

@ -1,97 +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\Regex;
use Symfony\Component\Validator\Constraints\RegexValidator;
use Symfony\Component\Validator\Validation;
class RegexValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new RegexValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Regex(array('pattern' => '/^[0-9]+$/')));
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Regex(array('pattern' => '/^[0-9]+$/')));
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Regex(array('pattern' => '/^[0-9]+$/')));
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value)
{
$constraint = new Regex(array('pattern' => '/^[0-9]+$/'));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
public function getValidValues()
{
return array(
array(0),
array('0'),
array('090909'),
array(90909),
);
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value)
{
$constraint = new Regex(array(
'pattern' => '/^[0-9]+$/',
'message' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$value.'"')
->assertRaised();
}
public function getInvalidValues()
{
return array(
array('abcd'),
array('090foo'),
);
}
}

View file

@ -1,107 +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\Time;
use Symfony\Component\Validator\Constraints\TimeValidator;
use Symfony\Component\Validator\Validation;
class TimeValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new TimeValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Time());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Time());
$this->assertNoViolation();
}
public function testDateTimeClassIsValid()
{
$this->validator->validate(new \DateTime(), new Time());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Time());
}
/**
* @dataProvider getValidTimes
*/
public function testValidTimes($time)
{
$this->validator->validate($time, new Time());
$this->assertNoViolation();
}
public function getValidTimes()
{
return array(
array('01:02:03'),
array('00:00:00'),
array('23:59:59'),
);
}
/**
* @dataProvider getInvalidTimes
*/
public function testInvalidTimes($time, $code)
{
$constraint = new Time(array(
'message' => 'myMessage',
));
$this->validator->validate($time, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$time.'"')
->setCode($code)
->assertRaised();
}
public function getInvalidTimes()
{
return array(
array('foobar', Time::INVALID_FORMAT_ERROR),
array('foobar 12:34:56', Time::INVALID_FORMAT_ERROR),
array('12:34:56 foobar', Time::INVALID_FORMAT_ERROR),
array('00:00', Time::INVALID_FORMAT_ERROR),
array('24:00:00', Time::INVALID_TIME_ERROR),
array('00:60:00', Time::INVALID_TIME_ERROR),
array('00:00:60', Time::INVALID_TIME_ERROR),
);
}
}

View file

@ -1,185 +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\Type;
use Symfony\Component\Validator\Constraints\TypeValidator;
use Symfony\Component\Validator\Validation;
class TypeValidatorTest extends AbstractConstraintValidatorTest
{
protected static $file;
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new TypeValidator();
}
public function testNullIsValid()
{
$constraint = new Type(array('type' => 'integer'));
$this->validator->validate(null, $constraint);
$this->assertNoViolation();
}
public function testEmptyIsValidIfString()
{
$constraint = new Type(array('type' => 'string'));
$this->validator->validate('', $constraint);
$this->assertNoViolation();
}
public function testEmptyIsInvalidIfNoString()
{
$constraint = new Type(array(
'type' => 'integer',
'message' => 'myMessage',
));
$this->validator->validate('', $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '""')
->setParameter('{{ type }}', 'integer')
->assertRaised();
}
/**
* @dataProvider getValidValues
*/
public function testValidValues($value, $type)
{
$constraint = new Type(array('type' => $type));
$this->validator->validate($value, $constraint);
$this->assertNoViolation();
}
public function getValidValues()
{
$object = new \stdClass();
$file = $this->createFile();
return array(
array(true, 'Boolean'),
array(false, 'Boolean'),
array(true, 'boolean'),
array(false, 'boolean'),
array(true, 'bool'),
array(false, 'bool'),
array(0, 'numeric'),
array('0', 'numeric'),
array(1.5, 'numeric'),
array('1.5', 'numeric'),
array(0, 'integer'),
array(1.5, 'float'),
array('12345', 'string'),
array(array(), 'array'),
array($object, 'object'),
array($object, 'stdClass'),
array($file, 'resource'),
array('12345', 'digit'),
array('12a34', 'alnum'),
array('abcde', 'alpha'),
array("\n\r\t", 'cntrl'),
array('arf12', 'graph'),
array('abcde', 'lower'),
array('ABCDE', 'upper'),
array('arf12', 'print'),
array('*&$()', 'punct'),
array("\n\r\t", 'space'),
array('AB10BC99', 'xdigit'),
);
}
/**
* @dataProvider getInvalidValues
*/
public function testInvalidValues($value, $type, $valueAsString)
{
$constraint = new Type(array(
'type' => $type,
'message' => 'myMessage',
));
$this->validator->validate($value, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', $valueAsString)
->setParameter('{{ type }}', $type)
->assertRaised();
}
public function getInvalidValues()
{
$object = new \stdClass();
$file = $this->createFile();
return array(
array('foobar', 'numeric', '"foobar"'),
array('foobar', 'boolean', '"foobar"'),
array('0', 'integer', '"0"'),
array('1.5', 'float', '"1.5"'),
array(12345, 'string', '12345'),
array($object, 'boolean', 'object'),
array($object, 'numeric', 'object'),
array($object, 'integer', 'object'),
array($object, 'float', 'object'),
array($object, 'string', 'object'),
array($object, 'resource', 'object'),
array($file, 'boolean', 'resource'),
array($file, 'numeric', 'resource'),
array($file, 'integer', 'resource'),
array($file, 'float', 'resource'),
array($file, 'string', 'resource'),
array($file, 'object', 'resource'),
array('12a34', 'digit', '"12a34"'),
array('1a#23', 'alnum', '"1a#23"'),
array('abcd1', 'alpha', '"abcd1"'),
array("\nabc", 'cntrl', "\"\nabc\""),
array("abc\n", 'graph', "\"abc\n\""),
array('abCDE', 'lower', '"abCDE"'),
array('ABcde', 'upper', '"ABcde"'),
array("\nabc", 'print', "\"\nabc\""),
array('abc&$!', 'punct', '"abc&$!"'),
array("\nabc", 'space', "\"\nabc\""),
array('AR1012', 'xdigit', '"AR1012"'),
);
}
protected function createFile()
{
if (!static::$file) {
static::$file = fopen(__FILE__, 'r');
}
return static::$file;
}
public static function tearDownAfterClass()
{
if (static::$file) {
fclose(static::$file);
static::$file = null;
}
}
}

View file

@ -1,179 +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\Url;
use Symfony\Component\Validator\Constraints\UrlValidator;
use Symfony\Component\Validator\Validation;
class UrlValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new UrlValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Url());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Url());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Url());
}
/**
* @dataProvider getValidUrls
*/
public function testValidUrls($url)
{
$this->validator->validate($url, new Url());
$this->assertNoViolation();
}
public function getValidUrls()
{
return array(
array('http://a.pl'),
array('http://www.google.com'),
array('http://www.google.com.'),
array('http://www.google.museum'),
array('https://google.com/'),
array('https://google.com:80/'),
array('http://www.example.coop/'),
array('http://www.test-example.com/'),
array('http://www.symfony.com/'),
array('http://symfony.fake/blog/'),
array('http://symfony.com/?'),
array('http://symfony.com/search?type=&q=url+validator'),
array('http://symfony.com/#'),
array('http://symfony.com/#?'),
array('http://www.symfony.com/doc/current/book/validation.html#supported-constraints'),
array('http://very.long.domain.name.com/'),
array('http://localhost/'),
array('http://127.0.0.1/'),
array('http://127.0.0.1:80/'),
array('http://[::1]/'),
array('http://[::1]:80/'),
array('http://[1:2:3::4:5:6:7]/'),
array('http://sãopaulo.com/'),
array('http://xn--sopaulo-xwa.com/'),
array('http://sãopaulo.com.br/'),
array('http://xn--sopaulo-xwa.com.br/'),
array('http://пример.испытание/'),
array('http://xn--e1afmkfd.xn--80akhbyknj4f/'),
array('http://مثال.إختبار/'),
array('http://xn--mgbh0fb.xn--kgbechtv/'),
array('http://例子.测试/'),
array('http://xn--fsqu00a.xn--0zwm56d/'),
array('http://例子.測試/'),
array('http://xn--fsqu00a.xn--g6w251d/'),
array('http://例え.テスト/'),
array('http://xn--r8jz45g.xn--zckzah/'),
array('http://مثال.آزمایشی/'),
array('http://xn--mgbh0fb.xn--hgbk6aj7f53bba/'),
array('http://실례.테스트/'),
array('http://xn--9n2bp8q.xn--9t4b11yi5a/'),
array('http://العربية.idn.icann.org/'),
array('http://xn--ogb.idn.icann.org/'),
array('http://xn--e1afmkfd.xn--80akhbyknj4f.xn--e1afmkfd/'),
array('http://xn--espaa-rta.xn--ca-ol-fsay5a/'),
array('http://xn--d1abbgf6aiiy.xn--p1ai/'),
array('http://☎.com/'),
array('http://username:password@symfony.com'),
array('http://user-name@symfony.com'),
);
}
/**
* @dataProvider getInvalidUrls
*/
public function testInvalidUrls($url)
{
$constraint = new Url(array(
'message' => 'myMessage',
));
$this->validator->validate($url, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$url.'"')
->assertRaised();
}
public function getInvalidUrls()
{
return array(
array('google.com'),
array('://google.com'),
array('http ://google.com'),
array('http:/google.com'),
array('http://goog_le.com'),
array('http://google.com::aa'),
array('http://google.com:aa'),
array('http://symfony.com?'),
array('http://symfony.com#'),
array('ftp://google.fr'),
array('faked://google.fr'),
array('http://127.0.0.1:aa/'),
array('ftp://[::1]/'),
array('http://[::1'),
array('http://hello.☎/'),
array('http://:password@symfony.com'),
array('http://:password@@symfony.com'),
array('http://username:passwordsymfony.com'),
array('http://usern@me:password@symfony.com'),
);
}
/**
* @dataProvider getValidCustomUrls
*/
public function testCustomProtocolIsValid($url)
{
$constraint = new Url(array(
'protocols' => array('ftp', 'file', 'git'),
));
$this->validator->validate($url, $constraint);
$this->assertNoViolation();
}
public function getValidCustomUrls()
{
return array(
array('ftp://google.com'),
array('file://127.0.0.1'),
array('git://[::1]/'),
);
}
}

View file

@ -1,211 +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\Uuid;
use Symfony\Component\Validator\Constraints\UuidValidator;
use Symfony\Component\Validator\Validation;
/**
* @author Colin O'Dell <colinodell@gmail.com>
*/
class UuidValidatorTest extends AbstractConstraintValidatorTest
{
protected function getApiVersion()
{
return Validation::API_VERSION_2_5;
}
protected function createValidator()
{
return new UuidValidator();
}
public function testNullIsValid()
{
$this->validator->validate(null, new Uuid());
$this->assertNoViolation();
}
public function testEmptyStringIsValid()
{
$this->validator->validate('', new Uuid());
$this->assertNoViolation();
}
/**
* @expectedException \Symfony\Component\Validator\Exception\UnexpectedTypeException
*/
public function testExpectsStringCompatibleType()
{
$this->validator->validate(new \stdClass(), new Uuid());
}
/**
* @dataProvider getValidStrictUuids
*/
public function testValidStrictUuids($uuid, $versions = null)
{
$constraint = new Uuid();
if (null !== $versions) {
$constraint->versions = $versions;
}
$this->validator->validate($uuid, $constraint);
$this->assertNoViolation();
}
public function getValidStrictUuids()
{
return array(
array('216fff40-98d9-11e3-a5e2-0800200c9a66'), // Version 1 UUID in lowercase
array('216fff40-98d9-11e3-a5e2-0800200c9a66', array(Uuid::V1_MAC)),
array('216FFF40-98D9-11E3-A5E2-0800200C9A66'), // Version 1 UUID in UPPERCASE
array('456daefb-5aa6-41b5-8dbc-068b05a8b201'), // Version 4 UUID in lowercase
array('456daEFb-5AA6-41B5-8DBC-068B05A8B201'), // Version 4 UUID in mixed case
array('456daEFb-5AA6-41B5-8DBC-068B05A8B201', array(Uuid::V4_RANDOM)),
);
}
/**
* @dataProvider getInvalidStrictUuids
*/
public function testInvalidStrictUuids($uuid, $code, $versions = null)
{
$constraint = new Uuid(array(
'message' => 'testMessage',
));
if (null !== $versions) {
$constraint->versions = $versions;
}
$this->validator->validate($uuid, $constraint);
$this->buildViolation('testMessage')
->setParameter('{{ value }}', '"'.$uuid.'"')
->setCode($code)
->assertRaised();
}
public function getInvalidStrictUuids()
{
return array(
array('216fff40-98d9-11e3-a5e2_0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR),
array('216gff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR),
array('216Gff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR),
array('216fff40-98d9-11e3-a5e-20800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216f-ff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216fff40-98d9-11e3-a5e2-0800-200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216fff40-98d9-11e3-a5e2-0800200c-9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216fff40-98d9-11e3-a5e20800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216fff4098d911e3a5e20800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216fff40-98d9-11e3-a5e2-0800200c9a6', Uuid::TOO_SHORT_ERROR),
array('216fff40-98d9-11e3-a5e2-0800200c9a666', Uuid::TOO_LONG_ERROR),
array('216fff40-98d9-01e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-61e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-71e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-81e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-91e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-a1e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-b1e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-c1e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-d1e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-e1e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-f1e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR),
array('216fff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR, array(Uuid::V2_DCE, Uuid::V3_MD5, Uuid::V4_RANDOM, Uuid::V5_SHA1)),
array('216fff40-98d9-21e3-a5e2-0800200c9a66', Uuid::INVALID_VERSION_ERROR, array(Uuid::V1_MAC, Uuid::V3_MD5, Uuid::V4_RANDOM, Uuid::V5_SHA1)),
array('216fff40-98d9-11e3-05e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-15e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-25e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-35e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-45e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-55e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-65e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-75e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-c5e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-d5e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-e5e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
array('216fff40-98d9-11e3-f5e2-0800200c9a66', Uuid::INVALID_VARIANT_ERROR),
// Non-standard UUID allowed by some other systems
array('{216fff40-98d9-11e3-a5e2-0800200c9a66}', Uuid::INVALID_CHARACTERS_ERROR),
array('[216fff40-98d9-11e3-a5e2-0800200c9a66]', Uuid::INVALID_CHARACTERS_ERROR),
);
}
/**
* @dataProvider getValidNonStrictUuids
*/
public function testValidNonStrictUuids($uuid)
{
$constraint = new Uuid(array(
'strict' => false,
));
$this->validator->validate($uuid, $constraint);
$this->assertNoViolation();
}
public function getValidNonStrictUuids()
{
return array(
array('216fff40-98d9-11e3-a5e2-0800200c9a66'), // Version 1 UUID in lowercase
array('216FFF40-98D9-11E3-A5E2-0800200C9A66'), // Version 1 UUID in UPPERCASE
array('456daefb-5aa6-41b5-8dbc-068b05a8b201'), // Version 4 UUID in lowercase
array('456DAEFb-5AA6-41B5-8DBC-068b05a8B201'), // Version 4 UUID in mixed case
// Non-standard UUIDs allowed by some other systems
array('216f-ff40-98d9-11e3-a5e2-0800-200c-9a66'), // Non-standard dash positions (every 4 chars)
array('216fff40-98d911e3-a5e20800-200c9a66'), // Non-standard dash positions (every 8 chars)
array('216fff4098d911e3a5e20800200c9a66'), // No dashes at all
array('{216fff40-98d9-11e3-a5e2-0800200c9a66}'), // Wrapped with curly braces
array('[216fff40-98d9-11e3-a5e2-0800200c9a66]'), // Wrapped with squared braces
);
}
/**
* @dataProvider getInvalidNonStrictUuids
*/
public function testInvalidNonStrictUuids($uuid, $code)
{
$constraint = new Uuid(array(
'strict' => false,
'message' => 'myMessage',
));
$this->validator->validate($uuid, $constraint);
$this->buildViolation('myMessage')
->setParameter('{{ value }}', '"'.$uuid.'"')
->setCode($code)
->assertRaised();
}
public function getInvalidNonStrictUuids()
{
return array(
array('216fff40-98d9-11e3-a5e2_0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR),
array('216gff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR),
array('216Gff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR),
array('216fff40-98d9-11e3-a5e2_0800200c9a6', Uuid::INVALID_CHARACTERS_ERROR),
array('216fff40-98d9-11e3-a5e-20800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR),
array('216fff40-98d9-11e3-a5e2-0800200c9a6', Uuid::TOO_SHORT_ERROR),
array('216fff40-98d9-11e3-a5e2-0800200c9a666', Uuid::TOO_LONG_ERROR),
);
}
}

View file

@ -1,28 +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\Valid;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class ValidTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \Symfony\Component\Validator\Exception\ConstraintDefinitionException
*/
public function testRejectGroupsOption()
{
new Valid(array('groups' => 'foo'));
}
}

View file

@ -1,24 +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\Fixtures;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
class CallbackClass
{
public static function callback($object, ExecutionContextInterface $context)
{
}
}

View file

@ -1,22 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
class ClassConstraint extends Constraint
{
public function getTargets()
{
return self::CLASS_CONSTRAINT;
}
}

View file

@ -1,31 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
/** @Annotation */
class ConstraintA extends Constraint
{
public $property1;
public $property2;
public function getDefaultOption()
{
return 'property2';
}
public function getTargets()
{
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
}
}

View file

@ -1,37 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\ExecutionContextInterface;
class ConstraintAValidator extends ConstraintValidator
{
public static $passedContext;
public function initialize(ExecutionContextInterface $context)
{
parent::initialize($context);
self::$passedContext = $context;
}
public function validate($value, Constraint $constraint)
{
if ('VALID' != $value) {
$this->context->addViolation('message', array('param' => 'value'));
return;
}
}
}

View file

@ -1,23 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
/** @Annotation */
class ConstraintB extends Constraint
{
public function getTargets()
{
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
}
}

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\Tests\Fixtures;
use Symfony\Component\Validator\Constraint;
/** @Annotation */
class ConstraintC extends Constraint
{
public $option1;
public function getRequiredOptions()
{
return array('option1');
}
public function getTargets()
{
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
}
}

View file

@ -1,31 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
/** @Annotation */
class ConstraintWithValue extends Constraint
{
public $property;
public $value;
public function getDefaultOption()
{
return 'property';
}
public function getTargets()
{
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
}
}

View file

@ -1,31 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
/** @Annotation */
class ConstraintWithValueAsDefault extends Constraint
{
public $property;
public $value;
public function getDefaultOption()
{
return 'value';
}
public function getTargets()
{
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
}
}

View file

@ -1,27 +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\Fixtures;
class Countable implements \Countable
{
private $content;
public function __construct(array $content)
{
$this->content = $content;
}
public function count()
{
return count($this->content);
}
}

View file

@ -1,70 +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\Fixtures;
/**
* This class is a hand written simplified version of PHP native `ArrayObject`
* class, to show that it behaves differently than the PHP native implementation.
*/
class CustomArrayObject implements \ArrayAccess, \IteratorAggregate, \Countable, \Serializable
{
private $array;
public function __construct(array $array = null)
{
$this->array = $array ?: array();
}
public function offsetExists($offset)
{
return array_key_exists($offset, $this->array);
}
public function offsetGet($offset)
{
return $this->array[$offset];
}
public function offsetSet($offset, $value)
{
if (null === $offset) {
$this->array[] = $value;
} else {
$this->array[$offset] = $value;
}
}
public function offsetUnset($offset)
{
unset($this->array[$offset]);
}
public function getIterator()
{
return new \ArrayIterator($this->array);
}
public function count()
{
return count($this->array);
}
public function serialize()
{
return serialize($this->array);
}
public function unserialize($serialized)
{
$this->array = (array) unserialize((string) $serialized);
}
}

View file

@ -1,100 +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\Fixtures;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\ExecutionContextInterface;
/**
* @Symfony\Component\Validator\Tests\Fixtures\ConstraintA
* @Assert\GroupSequence({"Foo", "Entity"})
* @Assert\Callback({"Symfony\Component\Validator\Tests\Fixtures\CallbackClass", "callback"})
*/
class Entity extends EntityParent implements EntityInterface
{
/**
* @Assert\NotNull
* @Assert\Range(min=3)
* @Assert\All({@Assert\NotNull, @Assert\Range(min=3)}),
* @Assert\All(constraints={@Assert\NotNull, @Assert\Range(min=3)})
* @Assert\Collection(fields={
* "foo" = {@Assert\NotNull, @Assert\Range(min=3)},
* "bar" = @Assert\Range(min=5)
* })
* @Assert\Choice(choices={"A", "B"}, message="Must be one of %choices%")
*/
public $firstName;
protected $lastName;
public $reference;
public $reference2;
private $internal;
public $data = 'Overridden data';
public $initialized = false;
public function __construct($internal = null)
{
$this->internal = $internal;
}
public function getInternal()
{
return $this->internal.' from getter';
}
public function setLastName($lastName)
{
$this->lastName = $lastName;
}
/**
* @Assert\NotNull
*/
public function getLastName()
{
return $this->lastName;
}
/**
* @Assert\IsTrue
*/
public function isValid()
{
return 'valid';
}
/**
* @Assert\IsTrue
*/
public function hasPermissions()
{
return 'permissions';
}
public function getData()
{
return 'Overridden data';
}
/**
* @Assert\Callback
*/
public function validateMe(ExecutionContextInterface $context)
{
}
/**
* @Assert\Callback
*/
public static function validateMeStatic($object, ExecutionContextInterface $context)
{
}
}

View file

@ -1,16 +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\Fixtures;
interface EntityInterface
{
}

View file

@ -1,31 +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\Fixtures;
use Symfony\Component\Validator\Constraints\NotNull;
class EntityParent
{
protected $firstName;
private $internal;
private $data = 'Data';
/**
* @NotNull
*/
protected $other;
public function getData()
{
return 'Data';
}
}

View file

@ -1,24 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
class FailingConstraint extends Constraint
{
public $message = 'Failed';
public function getTargets()
{
return array(self::PROPERTY_CONSTRAINT, self::CLASS_CONSTRAINT);
}
}

View file

@ -1,23 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class FailingConstraintValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
$this->context->addViolation($constraint->message, array());
}
}

View file

@ -1,26 +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\Fixtures;
use Symfony\Component\Validator\Mapping\ClassMetadata;
class FakeClassMetadata extends ClassMetadata
{
public function addCustomPropertyMetadata($propertyName, $metadata)
{
if (!isset($this->members[$propertyName])) {
$this->members[$propertyName] = array();
}
$this->members[$propertyName][] = $metadata;
}
}

View file

@ -1,72 +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\Fixtures;
use Symfony\Component\Validator\Exception\NoSuchMetadataException;
use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\MetadataInterface;
class FakeMetadataFactory implements MetadataFactoryInterface
{
protected $metadatas = array();
public function getMetadataFor($class)
{
$hash = null;
if (is_object($class)) {
$hash = spl_object_hash($class);
$class = get_class($class);
}
if (!is_string($class)) {
throw new NoSuchMetadataException(sprintf('No metadata for type %s', gettype($class)));
}
if (!isset($this->metadatas[$class])) {
if (isset($this->metadatas[$hash])) {
return $this->metadatas[$hash];
}
throw new NoSuchMetadataException(sprintf('No metadata for "%s"', $class));
}
return $this->metadatas[$class];
}
public function hasMetadataFor($class)
{
$hash = null;
if (is_object($class)) {
$hash = spl_object_hash($class);
$class = get_class($class);
}
if (!is_string($class)) {
return false;
}
return isset($this->metadatas[$class]) || isset($this->metadatas[$hash]);
}
public function addMetadata($metadata)
{
$this->metadatas[$metadata->getClassName()] = $metadata;
}
public function addMetadataForValue($value, MetadataInterface $metadata)
{
$key = is_object($value) ? spl_object_hash($value) : $value;
$this->metadatas[$key] = $metadata;
}
}

View file

@ -1,39 +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\Fixtures;
use Symfony\Component\Validator\Mapping\Loader\FilesLoader as BaseFilesLoader;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
abstract class FilesLoader extends BaseFilesLoader
{
protected $timesCalled = 0;
protected $loader;
public function __construct(array $paths, LoaderInterface $loader)
{
$this->loader = $loader;
parent::__construct($paths);
}
protected function getFileLoaderInstance($file)
{
++$this->timesCalled;
return $this->loader;
}
public function getTimesCalled()
{
return $this->timesCalled;
}
}

View file

@ -1,36 +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\Fixtures;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\GroupSequenceProviderInterface;
/**
* @Assert\GroupSequenceProvider
*/
class GroupSequenceProviderEntity implements GroupSequenceProviderInterface
{
public $firstName;
public $lastName;
protected $sequence = array();
public function __construct($sequence)
{
$this->sequence = $sequence;
}
public function getGroupSequence()
{
return $this->sequence;
}
}

View file

@ -1,18 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
class InvalidConstraint extends Constraint
{
}

View file

@ -1,16 +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\Fixtures;
class InvalidConstraintValidator
{
}

View file

@ -1,20 +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\Fixtures;
use Symfony\Component\Validator\ClassBasedInterface;
use Symfony\Component\Validator\MetadataInterface;
use Symfony\Component\Validator\PropertyMetadataContainerInterface;
interface LegacyClassMetadata extends MetadataInterface, PropertyMetadataContainerInterface, ClassBasedInterface
{
}

View file

@ -1,22 +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\Fixtures;
use Symfony\Component\Validator\Constraint;
class PropertyConstraint extends Constraint
{
public function getTargets()
{
return self::PROPERTY_CONSTRAINT;
}
}

View file

@ -1,29 +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\Fixtures;
class Reference
{
public $value;
private $privateValue;
public function setPrivateValue($privateValue)
{
$this->privateValue = $privateValue;
}
public function getPrivateValue()
{
return $this->privateValue;
}
}

View file

@ -1,70 +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\Fixtures;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\GlobalExecutionContextInterface;
use Symfony\Component\Validator\ValidationVisitorInterface;
/**
* @since 2.5.3
*
* @author Bernhard Schussek <bschussek@gmail.com>
*
* @deprecated since version 2.5, to be removed in 3.0
*/
class StubGlobalExecutionContext implements GlobalExecutionContextInterface
{
private $violations;
private $root;
private $visitor;
public function __construct($root = null, ValidationVisitorInterface $visitor = null)
{
$this->violations = new ConstraintViolationList();
$this->root = $root;
$this->visitor = $visitor;
}
public function getViolations()
{
return $this->violations;
}
public function setRoot($root)
{
$this->root = $root;
}
public function getRoot()
{
return $this->root;
}
public function setVisitor(ValidationVisitorInterface $visitor)
{
$this->visitor = $visitor;
}
public function getVisitor()
{
return $this->visitor;
}
public function getValidatorFactory()
{
}
public function getMetadataFactory()
{
}
}

View file

@ -1,334 +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\Constraints\Collection;
use Symfony\Component\Validator\Constraints\All;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\ConstraintViolationList;
use Symfony\Component\Validator\ExecutionContext;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\ValidationVisitor;
/**
* @group legacy
*/
class LegacyExecutionContextTest extends \PHPUnit_Framework_TestCase
{
const TRANS_DOMAIN = 'trans_domain';
private $visitor;
private $violations;
private $metadata;
private $metadataFactory;
private $globalContext;
private $translator;
/**
* @var ExecutionContext
*/
private $context;
protected function setUp()
{
$this->visitor = $this->getMockBuilder('Symfony\Component\Validator\ValidationVisitor')
->disableOriginalConstructor()
->getMock();
$this->violations = new ConstraintViolationList();
$this->metadata = $this->getMock('Symfony\Component\Validator\MetadataInterface');
$this->metadataFactory = $this->getMock('Symfony\Component\Validator\MetadataFactoryInterface');
$this->globalContext = $this->getMock('Symfony\Component\Validator\GlobalExecutionContextInterface');
$this->globalContext->expects($this->any())
->method('getRoot')
->will($this->returnValue('Root'));
$this->globalContext->expects($this->any())
->method('getViolations')
->will($this->returnValue($this->violations));
$this->globalContext->expects($this->any())
->method('getVisitor')
->will($this->returnValue($this->visitor));
$this->globalContext->expects($this->any())
->method('getMetadataFactory')
->will($this->returnValue($this->metadataFactory));
$this->translator = $this->getMock('Symfony\Component\Translation\TranslatorInterface');
$this->context = new ExecutionContext($this->globalContext, $this->translator, self::TRANS_DOMAIN, $this->metadata, 'currentValue', 'Group', 'foo.bar');
}
protected function tearDown()
{
$this->globalContext = 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('Group', $this->context->getGroup());
}
public function testClone()
{
$clone = clone $this->context;
// Cloning the context keeps the reference to the original violation
// list. This way we can efficiently duplicate context instances during
// the validation run and only modify the properties that need to be
// changed.
$this->assertSame($this->context->getViolations(), $clone->getViolations());
}
public function testAddViolation()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array('foo' => 'bar'))
->will($this->returnValue('Translated error'));
$this->context->addViolation('Error', array('foo' => 'bar'), 'invalid');
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array('foo' => 'bar'),
'Root',
'foo.bar',
'invalid'
),
)), $this->context->getViolations());
}
public function testAddViolationUsesPreconfiguredValueIfNotPassed()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array())
->will($this->returnValue('Translated error'));
$this->context->addViolation('Error');
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array(),
'Root',
'foo.bar',
'currentValue'
),
)), $this->context->getViolations());
}
public function testAddViolationUsesPassedNullValue()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array('foo1' => 'bar1'))
->will($this->returnValue('Translated error'));
$this->translator->expects($this->once())
->method('transChoice')
->with('Choice error', 1, array('foo2' => 'bar2'))
->will($this->returnValue('Translated choice error'));
// passed null value should override preconfigured value "invalid"
$this->context->addViolation('Error', array('foo1' => 'bar1'), null);
$this->context->addViolation('Choice error', array('foo2' => 'bar2'), null, 1);
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array('foo1' => 'bar1'),
'Root',
'foo.bar',
null
),
new ConstraintViolation(
'Translated choice error',
'Choice error',
array('foo2' => 'bar2'),
'Root',
'foo.bar',
null,
1
),
)), $this->context->getViolations());
}
public function testAddViolationAt()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array('foo' => 'bar'))
->will($this->returnValue('Translated error'));
// override preconfigured property path
$this->context->addViolationAt('bam.baz', 'Error', array('foo' => 'bar'), 'invalid');
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array('foo' => 'bar'),
'Root',
'foo.bar.bam.baz',
'invalid'
),
)), $this->context->getViolations());
}
public function testAddViolationAtUsesPreconfiguredValueIfNotPassed()
{
$this->translator->expects($this->once())
->method('trans')
->with('Error', array())
->will($this->returnValue('Translated error'));
$this->context->addViolationAt('bam.baz', 'Error');
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array(),
'Root',
'foo.bar.bam.baz',
'currentValue'
),
)), $this->context->getViolations());
}
public function testAddViolationAtUsesPassedNullValue()
{
$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', 2, array('foo' => 'bar'))
->will($this->returnValue('Translated choice error'));
// passed null value should override preconfigured value "invalid"
$this->context->addViolationAt('bam.baz', 'Error', array('foo' => 'bar'), null);
$this->context->addViolationAt('bam.baz', 'Choice error', array('foo' => 'bar'), null, 2);
$this->assertEquals(new ConstraintViolationList(array(
new ConstraintViolation(
'Translated error',
'Error',
array('foo' => 'bar'),
'Root',
'foo.bar.bam.baz',
null
),
new ConstraintViolation(
'Translated choice error',
'Choice error',
array('foo' => 'bar'),
'Root',
'foo.bar.bam.baz',
null,
2
),
)), $this->context->getViolations());
}
public function testAddViolationPluralTranslationError()
{
$this->translator->expects($this->once())
->method('transChoice')
->with('foo')
->will($this->throwException(new \InvalidArgumentException()));
$this->translator->expects($this->once())
->method('trans')
->with('foo');
$this->context->addViolation('foo', array(), null, 2);
}
public function testGetPropertyPath()
{
$this->assertEquals('foo.bar', $this->context->getPropertyPath());
}
public function testGetPropertyPathWithIndexPath()
{
$this->assertEquals('foo.bar[bam]', $this->context->getPropertyPath('[bam]'));
}
public function testGetPropertyPathWithEmptyPath()
{
$this->assertEquals('foo.bar', $this->context->getPropertyPath(''));
}
public function testGetPropertyPathWithEmptyCurrentPropertyPath()
{
$this->context = new ExecutionContext($this->globalContext, $this->translator, self::TRANS_DOMAIN, $this->metadata, 'currentValue', 'Group', '');
$this->assertEquals('bam.baz', $this->context->getPropertyPath('bam.baz'));
}
public function testGetPropertyPathWithNestedCollectionsAndAllMixed()
{
$constraints = new Collection(array(
'shelves' => new All(array('constraints' => array(
new Collection(array(
'name' => new ConstraintA(),
'books' => new All(array('constraints' => array(
new ConstraintA(),
))),
)),
))),
'name' => new ConstraintA(),
));
$data = array(
'shelves' => array(
array(
'name' => 'Research',
'books' => array('foo', 'bar'),
),
array(
'name' => 'VALID',
'books' => array('foozy', 'VALID', 'bazzy'),
),
),
'name' => 'Library',
);
$expectedViolationPaths = array(
'[shelves][0][name]',
'[shelves][0][books][0]',
'[shelves][0][books][1]',
'[shelves][1][books][0]',
'[shelves][1][books][2]',
'[name]',
);
$visitor = new ValidationVisitor('Root', $this->metadataFactory, new ConstraintValidatorFactory(), $this->translator);
$context = new ExecutionContext($visitor, $this->translator, self::TRANS_DOMAIN);
$context->validateValue($data, $constraints);
foreach ($context->getViolations() as $violation) {
$violationPaths[] = $violation->getPropertyPath();
}
$this->assertEquals($expectedViolationPaths, $violationPaths);
}
}
class ExecutionContextTest_TestClass
{
public $myProperty;
}

View file

@ -1,42 +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\Translation\IdentityTranslator;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\ConstraintValidatorFactory;
use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Tests\Validator\AbstractLegacyApiTest;
use Symfony\Component\Validator\Validator as LegacyValidator;
/**
* @group legacy
*/
class LegacyValidatorTest extends AbstractLegacyApiTest
{
protected function createValidator(MetadataFactoryInterface $metadataFactory, array $objectInitializers = array())
{
$translator = new IdentityTranslator();
$translator->setLocale('en');
return new LegacyValidator($metadataFactory, new ConstraintValidatorFactory(), $translator, 'validators', $objectInitializers);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\ValidatorException
*/
public function testValidateValueRejectsValid()
{
$this->validator->validateValue(new Entity(), new Valid());
}
}

View file

@ -1,84 +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\Mapping\Cache;
use Doctrine\Common\Cache\ArrayCache;
use Symfony\Component\Validator\Mapping\Cache\DoctrineCache;
class DoctrineCacheTest extends \PHPUnit_Framework_TestCase
{
private $cache;
public function testWrite()
{
$meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
->disableOriginalConstructor()
->setMethods(array('getClassName'))
->getMock();
$meta->expects($this->once())
->method('getClassName')
->will($this->returnValue('bar'));
$this->cache->write($meta);
$this->assertInstanceOf(
'Symfony\\Component\\Validator\\Mapping\\ClassMetadata',
$this->cache->read('bar'),
'write() stores metadata'
);
}
public function testHas()
{
$meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
->disableOriginalConstructor()
->setMethods(array('getClassName'))
->getMock();
$meta->expects($this->once())
->method('getClassName')
->will($this->returnValue('bar'));
$this->assertFalse($this->cache->has('bar'), 'has() returns false when there is no entry');
$this->cache->write($meta);
$this->assertTrue($this->cache->has('bar'), 'has() returns true when the is an entry');
}
public function testRead()
{
$meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
->disableOriginalConstructor()
->setMethods(array('getClassName'))
->getMock();
$meta->expects($this->once())
->method('getClassName')
->will($this->returnValue('bar'));
$this->assertFalse($this->cache->read('bar'), 'read() returns false when there is no entry');
$this->cache->write($meta);
$this->assertInstanceOf(
'Symfony\\Component\\Validator\\Mapping\\ClassMetadata',
$this->cache->read('bar'),
'read() returns metadata'
);
}
protected function setUp()
{
$this->cache = new DoctrineCache(new ArrayCache());
}
}

View file

@ -1,81 +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\Mapping\Cache;
use Symfony\Component\Validator\Mapping\Cache\ApcCache;
/**
* @group legacy
*/
class LegacyApcCacheTest extends \PHPUnit_Framework_TestCase
{
protected function setUp()
{
if (!extension_loaded('apc') || !ini_get('apc.enable_cli')) {
$this->markTestSkipped('APC is not loaded.');
}
}
public function testWrite()
{
$meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
->disableOriginalConstructor()
->setMethods(array('getClassName'))
->getMock();
$meta->expects($this->once())
->method('getClassName')
->will($this->returnValue('bar'));
$cache = new ApcCache('foo');
$cache->write($meta);
$this->assertInstanceOf('Symfony\\Component\\Validator\\Mapping\\ClassMetadata', apc_fetch('foobar'), '->write() stores metadata in APC');
}
public function testHas()
{
$meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
->disableOriginalConstructor()
->setMethods(array('getClassName'))
->getMock();
$meta->expects($this->once())
->method('getClassName')
->will($this->returnValue('bar'));
apc_delete('foobar');
$cache = new ApcCache('foo');
$this->assertFalse($cache->has('bar'), '->has() returns false when there is no entry');
$cache->write($meta);
$this->assertTrue($cache->has('bar'), '->has() returns true when the is an entry');
}
public function testRead()
{
$meta = $this->getMockBuilder('Symfony\\Component\\Validator\\Mapping\\ClassMetadata')
->disableOriginalConstructor()
->setMethods(array('getClassName'))
->getMock();
$meta->expects($this->once())
->method('getClassName')
->will($this->returnValue('bar'));
$cache = new ApcCache('foo');
$cache->write($meta);
$this->assertInstanceOf('Symfony\\Component\\Validator\\Mapping\\ClassMetadata', $cache->read('bar'), '->read() returns metadata');
}
}

View file

@ -1,280 +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\Mapping;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
use Symfony\Component\Validator\Tests\Fixtures\PropertyConstraint;
class ClassMetadataTest extends \PHPUnit_Framework_TestCase
{
const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
const PARENTCLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';
const PROVIDERCLASS = 'Symfony\Component\Validator\Tests\Fixtures\GroupSequenceProviderEntity';
protected $metadata;
protected function setUp()
{
$this->metadata = new ClassMetadata(self::CLASSNAME);
}
protected function tearDown()
{
$this->metadata = null;
}
public function testAddConstraintDoesNotAcceptValid()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
$this->metadata->addConstraint(new Valid());
}
public function testAddConstraintRequiresClassConstraints()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\ConstraintDefinitionException');
$this->metadata->addConstraint(new PropertyConstraint());
}
public function testAddPropertyConstraints()
{
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->metadata->addPropertyConstraint('lastName', new ConstraintB());
$this->assertEquals(array('firstName', 'lastName'), $this->metadata->getConstrainedProperties());
}
public function testAddMultiplePropertyConstraints()
{
$this->metadata->addPropertyConstraints('lastName', array(new ConstraintA(), new ConstraintB()));
$constraints = array(
new ConstraintA(array('groups' => array('Default', 'Entity'))),
new ConstraintB(array('groups' => array('Default', 'Entity'))),
);
$properties = $this->metadata->getPropertyMetadata('lastName');
$this->assertCount(1, $properties);
$this->assertEquals('lastName', $properties[0]->getName());
$this->assertEquals($constraints, $properties[0]->getConstraints());
}
public function testAddGetterConstraints()
{
$this->metadata->addGetterConstraint('lastName', new ConstraintA());
$this->metadata->addGetterConstraint('lastName', new ConstraintB());
$constraints = array(
new ConstraintA(array('groups' => array('Default', 'Entity'))),
new ConstraintB(array('groups' => array('Default', 'Entity'))),
);
$properties = $this->metadata->getPropertyMetadata('lastName');
$this->assertCount(1, $properties);
$this->assertEquals('getLastName', $properties[0]->getName());
$this->assertEquals($constraints, $properties[0]->getConstraints());
}
public function testAddMultipleGetterConstraints()
{
$this->metadata->addGetterConstraints('lastName', array(new ConstraintA(), new ConstraintB()));
$constraints = array(
new ConstraintA(array('groups' => array('Default', 'Entity'))),
new ConstraintB(array('groups' => array('Default', 'Entity'))),
);
$properties = $this->metadata->getPropertyMetadata('lastName');
$this->assertCount(1, $properties);
$this->assertEquals('getLastName', $properties[0]->getName());
$this->assertEquals($constraints, $properties[0]->getConstraints());
}
public function testMergeConstraintsMergesClassConstraints()
{
$parent = new ClassMetadata(self::PARENTCLASS);
$parent->addConstraint(new ConstraintA());
$this->metadata->mergeConstraints($parent);
$this->metadata->addConstraint(new ConstraintA());
$constraints = array(
new ConstraintA(array('groups' => array(
'Default',
'EntityParent',
'Entity',
))),
new ConstraintA(array('groups' => array(
'Default',
'Entity',
))),
);
$this->assertEquals($constraints, $this->metadata->getConstraints());
}
public function testMergeConstraintsMergesMemberConstraints()
{
$parent = new ClassMetadata(self::PARENTCLASS);
$parent->addPropertyConstraint('firstName', new ConstraintA());
$this->metadata->mergeConstraints($parent);
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$constraints = array(
new ConstraintA(array('groups' => array(
'Default',
'EntityParent',
'Entity',
))),
new ConstraintA(array('groups' => array(
'Default',
'Entity',
))),
);
$members = $this->metadata->getPropertyMetadata('firstName');
$this->assertCount(1, $members);
$this->assertEquals(self::PARENTCLASS, $members[0]->getClassName());
$this->assertEquals($constraints, $members[0]->getConstraints());
}
public function testMemberMetadatas()
{
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->assertTrue($this->metadata->hasPropertyMetadata('firstName'));
$this->assertFalse($this->metadata->hasPropertyMetadata('non_existent_field'));
}
public function testMergeConstraintsKeepsPrivateMembersSeparate()
{
$parent = new ClassMetadata(self::PARENTCLASS);
$parent->addPropertyConstraint('internal', new ConstraintA());
$this->metadata->mergeConstraints($parent);
$this->metadata->addPropertyConstraint('internal', new ConstraintA());
$parentConstraints = array(
new ConstraintA(array('groups' => array(
'Default',
'EntityParent',
'Entity',
))),
);
$constraints = array(
new ConstraintA(array('groups' => array(
'Default',
'Entity',
))),
);
$members = $this->metadata->getPropertyMetadata('internal');
$this->assertCount(2, $members);
$this->assertEquals(self::PARENTCLASS, $members[0]->getClassName());
$this->assertEquals($parentConstraints, $members[0]->getConstraints());
$this->assertEquals(self::CLASSNAME, $members[1]->getClassName());
$this->assertEquals($constraints, $members[1]->getConstraints());
}
public function testGetReflectionClass()
{
$reflClass = new \ReflectionClass(self::CLASSNAME);
$this->assertEquals($reflClass, $this->metadata->getReflectionClass());
}
public function testSerialize()
{
$this->metadata->addConstraint(new ConstraintA(array('property1' => 'A')));
$this->metadata->addConstraint(new ConstraintB(array('groups' => 'TestGroup')));
$this->metadata->addPropertyConstraint('firstName', new ConstraintA());
$this->metadata->addGetterConstraint('lastName', new ConstraintB());
$metadata = unserialize(serialize($this->metadata));
$this->assertEquals($this->metadata, $metadata);
}
public function testGroupSequencesWorkIfContainingDefaultGroup()
{
$this->metadata->setGroupSequence(array('Foo', $this->metadata->getDefaultGroup()));
}
public function testGroupSequencesFailIfNotContainingDefaultGroup()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\GroupDefinitionException');
$this->metadata->setGroupSequence(array('Foo', 'Bar'));
}
public function testGroupSequencesFailIfContainingDefault()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\GroupDefinitionException');
$this->metadata->setGroupSequence(array('Foo', $this->metadata->getDefaultGroup(), Constraint::DEFAULT_GROUP));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException
*/
public function testGroupSequenceFailsIfGroupSequenceProviderIsSet()
{
$metadata = new ClassMetadata(self::PROVIDERCLASS);
$metadata->setGroupSequenceProvider(true);
$metadata->setGroupSequence(array('GroupSequenceProviderEntity', 'Foo'));
}
/**
* @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException
*/
public function testGroupSequenceProviderFailsIfGroupSequenceIsSet()
{
$metadata = new ClassMetadata(self::PROVIDERCLASS);
$metadata->setGroupSequence(array('GroupSequenceProviderEntity', 'Foo'));
$metadata->setGroupSequenceProvider(true);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\GroupDefinitionException
*/
public function testGroupSequenceProviderFailsIfDomainClassIsInvalid()
{
$metadata = new ClassMetadata('stdClass');
$metadata->setGroupSequenceProvider(true);
}
public function testGroupSequenceProvider()
{
$metadata = new ClassMetadata(self::PROVIDERCLASS);
$metadata->setGroupSequenceProvider(true);
$this->assertTrue($metadata->isGroupSequenceProvider());
}
/**
* https://github.com/symfony/symfony/issues/11604.
*/
public function testGetPropertyMetadataReturnsEmptyArrayWithoutConfiguredMetadata()
{
$this->assertCount(0, $this->metadata->getPropertyMetadata('foo'), '->getPropertyMetadata() returns an empty collection if no metadata is configured for the given property');
}
}

View file

@ -1,33 +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\Mapping\Factory;
use Symfony\Component\Validator\Mapping\Factory\BlackHoleMetadataFactory;
class BlackHoleMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
/**
* @expectedException \LogicException
*/
public function testGetMetadataForThrowsALogicException()
{
$metadataFactory = new BlackHoleMetadataFactory();
$metadataFactory->getMetadataFor('foo');
}
public function testHasMetadataForReturnsFalse()
{
$metadataFactory = new BlackHoleMetadataFactory();
$this->assertFalse($metadataFactory->hasMetadataFor('foo'));
}
}

View file

@ -1,118 +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\Mapping\Factory;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Factory\LazyLoadingMetadataFactory;
use Symfony\Component\Validator\Mapping\Loader\LoaderInterface;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
class LazyLoadingMetadataFactoryTest extends \PHPUnit_Framework_TestCase
{
const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
const PARENTCLASS = 'Symfony\Component\Validator\Tests\Fixtures\EntityParent';
public function testLoadClassMetadata()
{
$factory = new LazyLoadingMetadataFactory(new TestLoader());
$metadata = $factory->getMetadataFor(self::PARENTCLASS);
$constraints = array(
new ConstraintA(array('groups' => array('Default', 'EntityParent'))),
);
$this->assertEquals($constraints, $metadata->getConstraints());
}
public function testMergeParentConstraints()
{
$factory = new LazyLoadingMetadataFactory(new TestLoader());
$metadata = $factory->getMetadataFor(self::CLASSNAME);
$constraints = array(
new ConstraintA(array('groups' => array(
'Default',
'EntityParent',
'Entity',
))),
new ConstraintA(array('groups' => array(
'Default',
'EntityInterface',
'Entity',
))),
new ConstraintA(array('groups' => array(
'Default',
'Entity',
))),
);
$this->assertEquals($constraints, $metadata->getConstraints());
}
public function testWriteMetadataToCache()
{
$cache = $this->getMock('Symfony\Component\Validator\Mapping\Cache\CacheInterface');
$factory = new LazyLoadingMetadataFactory(new TestLoader(), $cache);
$tester = $this;
$constraints = array(
new ConstraintA(array('groups' => array('Default', 'EntityParent'))),
);
$cache->expects($this->never())
->method('has');
$cache->expects($this->once())
->method('read')
->with($this->equalTo(self::PARENTCLASS))
->will($this->returnValue(false));
$cache->expects($this->once())
->method('write')
->will($this->returnCallback(function ($metadata) use ($tester, $constraints) {
$tester->assertEquals($constraints, $metadata->getConstraints());
}));
$metadata = $factory->getMetadataFor(self::PARENTCLASS);
$this->assertEquals(self::PARENTCLASS, $metadata->getClassName());
$this->assertEquals($constraints, $metadata->getConstraints());
}
public function testReadMetadataFromCache()
{
$loader = $this->getMock('Symfony\Component\Validator\Mapping\Loader\LoaderInterface');
$cache = $this->getMock('Symfony\Component\Validator\Mapping\Cache\CacheInterface');
$factory = new LazyLoadingMetadataFactory($loader, $cache);
$tester = $this;
$metadata = new ClassMetadata(self::PARENTCLASS);
$metadata->addConstraint(new ConstraintA());
$loader->expects($this->never())
->method('loadClassMetadata');
$cache->expects($this->never())
->method('has');
$cache->expects($this->once())
->method('read')
->will($this->returnValue($metadata));
$this->assertEquals($metadata, $factory->getMetadataFor(self::PARENTCLASS));
}
}
class TestLoader implements LoaderInterface
{
public function loadClassMetadata(ClassMetadata $metadata)
{
$metadata->addConstraint(new ConstraintA());
}
}

View file

@ -1,62 +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\Mapping;
use Symfony\Component\Validator\Mapping\GetterMetadata;
use Symfony\Component\Validator\Tests\Fixtures\Entity;
class GetterMetadataTest extends \PHPUnit_Framework_TestCase
{
const CLASSNAME = 'Symfony\Component\Validator\Tests\Fixtures\Entity';
public function testInvalidPropertyName()
{
$this->setExpectedException('Symfony\Component\Validator\Exception\ValidatorException');
new GetterMetadata(self::CLASSNAME, 'foobar');
}
public function testGetPropertyValueFromPublicGetter()
{
// private getters don't work yet because ReflectionMethod::setAccessible()
// does not exist yet in a stable PHP release
$entity = new Entity('foobar');
$metadata = new GetterMetadata(self::CLASSNAME, 'internal');
$this->assertEquals('foobar from getter', $metadata->getPropertyValue($entity));
}
public function testGetPropertyValueFromOverriddenPublicGetter()
{
$entity = new Entity();
$metadata = new GetterMetadata(self::CLASSNAME, 'data');
$this->assertEquals('Overridden data', $metadata->getPropertyValue($entity));
}
public function testGetPropertyValueFromIsser()
{
$entity = new Entity();
$metadata = new GetterMetadata(self::CLASSNAME, 'valid');
$this->assertEquals('valid', $metadata->getPropertyValue($entity));
}
public function testGetPropertyValueFromHasser()
{
$entity = new Entity();
$metadata = new GetterMetadata(self::CLASSNAME, 'permissions');
$this->assertEquals('permissions', $metadata->getPropertyValue($entity));
}
}

View file

@ -1,78 +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\Mapping;
use Symfony\Component\Validator\Mapping\ElementMetadata;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintB;
/**
* @group legacy
*/
class LegacyElementMetadataTest extends \PHPUnit_Framework_TestCase
{
protected $metadata;
protected function setUp()
{
$this->metadata = new TestElementMetadata();
}
protected function tearDown()
{
$this->metadata = null;
}
public function testAddConstraints()
{
$this->metadata->addConstraint($constraint1 = new ConstraintA());
$this->metadata->addConstraint($constraint2 = new ConstraintA());
$this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints());
}
public function testMultipleConstraintsOfTheSameType()
{
$constraint1 = new ConstraintA(array('property1' => 'A'));
$constraint2 = new ConstraintA(array('property1' => 'B'));
$this->metadata->addConstraint($constraint1);
$this->metadata->addConstraint($constraint2);
$this->assertEquals(array($constraint1, $constraint2), $this->metadata->getConstraints());
}
public function testFindConstraintsByGroup()
{
$constraint1 = new ConstraintA(array('groups' => 'TestGroup'));
$constraint2 = new ConstraintB();
$this->metadata->addConstraint($constraint1);
$this->metadata->addConstraint($constraint2);
$this->assertEquals(array($constraint1), $this->metadata->findConstraints('TestGroup'));
}
public function testSerialize()
{
$this->metadata->addConstraint(new ConstraintA(array('property1' => 'A')));
$this->metadata->addConstraint(new ConstraintB(array('groups' => 'TestGroup')));
$metadata = unserialize(serialize($this->metadata));
$this->assertEquals($this->metadata, $metadata);
}
}
class TestElementMetadata extends ElementMetadata
{
}

Some files were not shown because too many files have changed in this diff Show more