Browse Source

Adding a validation method to validate the count of a value

Florian Krämer 10 years ago
parent
commit
f0559420a1
2 changed files with 52 additions and 0 deletions
  1. 29 0
      src/Validation/Validation.php
  2. 23 0
      tests/TestCase/Validation/ValidationTest.php

+ 29 - 0
src/Validation/Validation.php

@@ -216,6 +216,35 @@ class Validation
     }
 
     /**
+     * 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.
      *
      * @param string $check1 if string is passed for, a string must also be passed for $check2

+ 23 - 0
tests/TestCase/Validation/ValidationTest.php

@@ -2762,4 +2762,27 @@ class ValidationTest extends TestCase
         // 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));
+    }
 }