From 2850abbef6c573fb730eb4a794eaea6539b4b1c0 Mon Sep 17 00:00:00 2001 From: Maksim Kotlyar Date: Fri, 13 Apr 2012 13:01:27 +0300 Subject: [PATCH] [Validator] add support of arrays and Countables to Size Validator. --- .../Validator/Constraints/SizeValidator.php | 4 +++ .../Tests/Constraints/SizeValidatorTest.php | 29 +++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/Symfony/Component/Validator/Constraints/SizeValidator.php b/src/Symfony/Component/Validator/Constraints/SizeValidator.php index db8bc65c6827b..75411997a522b 100644 --- a/src/Symfony/Component/Validator/Constraints/SizeValidator.php +++ b/src/Symfony/Component/Validator/Constraints/SizeValidator.php @@ -35,6 +35,10 @@ public function isValid($value, Constraint $constraint) return true; } + if (is_array($value) || $value instanceof \Countable) { + $value = count($value); + } + if (!is_numeric($value)) { $this->context->addViolation($constraint->invalidMessage, array( '{{ value }}' => $value, diff --git a/src/Symfony/Component/Validator/Tests/Constraints/SizeValidatorTest.php b/src/Symfony/Component/Validator/Tests/Constraints/SizeValidatorTest.php index 2764d325ce5ef..caffaf56ffb11 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/SizeValidatorTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/SizeValidatorTest.php @@ -48,6 +48,14 @@ public function testValidValues($value) public function getValidValues() { + $array = range(1, 15); + $countableMock = $this->getMock('Countable'); + $countableMock + ->expects($this->any()) + ->method('count') + ->will($this->returnValue(15)) + ; + return array( array(10.00001), array(19.99999), @@ -57,6 +65,8 @@ public function getValidValues() array(20), array(10.0), array(20.0), + array($array), + array($countableMock) ); } @@ -74,12 +84,31 @@ public function testInvalidValues($value) public function getInvalidValues() { + $smallerArray = range(1, 9); + $biggerArray = range(1, 21); + $smallerCountableMock = $this->getMock('Countable'); + $smallerCountableMock + ->expects($this->any()) + ->method('count') + ->will($this->returnValue(9)) + ; + $biggerCountableMock = $this->getMock('Countable'); + $biggerCountableMock + ->expects($this->any()) + ->method('count') + ->will($this->returnValue(21)) + ; + return array( array(9.999999), array(20.000001), array('9.999999'), array('20.000001'), array(new \stdClass()), + array($smallerArray), + array($biggerArray), + array($smallerCountableMock), + array($biggerCountableMock) ); }