Browse Source

Merge branch 'feature/count-validation' of https://github.com/burzum/cakephp into validate-numelements

Jose Lorenzo Rodriguez 10 years ago
parent
commit
6d7da55ad6
2 changed files with 43 additions and 0 deletions
  1. 20 0
      src/Validation/Validation.php
  2. 23 0
      tests/TestCase/Validation/ValidationTest.php

+ 20 - 0
src/Validation/Validation.php

@@ -216,6 +216,26 @@ 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 $expectedCount The expected count value.
+     * @return bool Success
+     */
+    public static function numElements($check1, $operator, $expectedCount)
+    {
+        if (!is_array($check1) || $check1 instanceof \Countable) {
+            return false;
+        }
+        return self::comparison(count($check1), $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 numElements
+     *
+     * @return void
+     */
+    public function testNumElements()
+    {
+        $array = ['cake', 'php'];
+        $this->assertTrue(Validation::numElements($array, '==', 2));
+        $this->assertFalse(Validation::numElements($array, '>', 3));
+        $this->assertFalse(Validation::numElements($array, '<', 1));
+
+        $callable = function() {
+            return '';
+        };
+
+        $this->assertFalse(Validation::numElements(null, '==', 0));
+        $this->assertFalse(Validation::numElements(new \stdClass(), '==', 0));
+        $this->assertFalse(Validation::numElements($callable, '==', 0));
+        $this->assertFalse(Validation::numElements(false, '==', 0));
+        $this->assertFalse(Validation::numElements(true, '==', 0));
+    }
 }