From f0559420a1b744db3d7d240eedaed48604ace89a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20Kr=C3=A4mer?= Date: Wed, 27 Apr 2016 02:17:59 +0200 Subject: [PATCH] Adding a validation method to validate the count of a value --- src/Validation/Validation.php | 29 ++++++++++++++++++++ tests/TestCase/Validation/ValidationTest.php | 23 ++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/src/Validation/Validation.php b/src/Validation/Validation.php index f625a7dd50a..6f10d78f8c7 100644 --- a/src/Validation/Validation.php +++ b/src/Validation/Validation.php @@ -215,6 +215,35 @@ public static function cc($check, $type = 'fast', $deep = false, $regex = null) return false; } + /** + * Used to check the count of a given value of type string, int, or array. + * + * If a string value is passed the string length is used as count. + * + * @param array|int|string $check1 The value to check the count on. + * @param string $operator Can be either a word or operand + * is greater >, is less <, greater or equal >= + * less or equal <=, is less <, equal to ==, not equal != + * @param int $check2 The expected count value. + * @return bool Success + */ + public static function count($check1, $operator, $expectedCount) + { + if (is_array($check1) || $check1 instanceof \Countable) { + $count = count($check1); + } elseif (is_string($check1)) { + $count = mb_strlen($check1); + } elseif (is_int($check1)) { + $count = $check1; + } + + if (!$count) { + return false; + } + + return self::comparison($count, $operator, $expectedCount); + } + /** * Used to compare 2 numeric values. * diff --git a/tests/TestCase/Validation/ValidationTest.php b/tests/TestCase/Validation/ValidationTest.php index 568eff10c6e..b67bca46767 100644 --- a/tests/TestCase/Validation/ValidationTest.php +++ b/tests/TestCase/Validation/ValidationTest.php @@ -2762,4 +2762,27 @@ public function testUtf8Extended() // Grinning face $this->assertTrue(Validation::utf8('some' . "\xf0\x9f\x98\x80" . 'value', ['extended' => true])); } + + /** + * Test count + * + * @return void + */ + public function testCount() + { + $array = ['cake', 'php']; + $this->assertTrue(Validation::count($array, '==', 2)); + $this->assertFalse(Validation::count($array, '>', 3)); + $this->assertFalse(Validation::count($array, '<', 1)); + + $string = 'cakephp'; + $this->assertTrue(Validation::count($string, '==', 7)); + $this->assertFalse(Validation::count($string, '>', 8)); + $this->assertFalse(Validation::count($string, '<', 1)); + + $int = 7; + $this->assertTrue(Validation::count($int, '==', 7)); + $this->assertFalse(Validation::count($int, '>', 8)); + $this->assertFalse(Validation::count($int, '<', 1)); + } }