Browse Source

adds validation for arrays

thinkingmedia 9 years ago
parent
commit
40499d4345

+ 11 - 0
src/Validation/Validation.php

@@ -1182,6 +1182,17 @@ class Validation
     }
 
     /**
+     * Check that the input value is an array.
+     *
+     * @param array $value
+     * @return bool
+     */
+    public static function isArray($value)
+    {
+        return is_array($value);
+    }
+
+    /**
      * Converts an array representing a date or datetime into a ISO string.
      * The arrays are typically sent for validation from a form generated by
      * the CakePHP FormHelper.

+ 17 - 0
src/Validation/Validator.php

@@ -1302,6 +1302,23 @@ class Validator implements ArrayAccess, IteratorAggregate, Countable
     }
 
     /**
+     * Add a validation rule to ensure that a field contains an array.
+     *
+     * @param string $field The field you want to apply the rule to.
+     * @param string|null $message The error message when the rule fails.
+     * @param string|callable|null $when Either 'create' or 'update' or a callable that returns
+     *   true when the validation rule should be applied.
+     * @return $this
+     */
+    public function isArray($field, $message = null, $when = null)
+    {
+        $extra = array_filter(['on' => $when, 'message' => $message]);
+        return $this->add($field, 'isArray', $extra + [
+                'rule' => 'isArray'
+            ]);
+    }
+
+    /**
      * Add a validation rule for a multiple select. Comparison is case sensitive by default.
      *
      * @param string $field The field you want to apply the rule to.

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

@@ -14,11 +14,13 @@
  */
 namespace Cake\Test\TestCase\Validation;
 
+use Cake\Collection\Collection;
 use Cake\Core\Configure;
 use Cake\Filesystem\File;
 use Cake\I18n\I18n;
 use Cake\TestSuite\TestCase;
 use Cake\Validation\Validation;
+use Cake\Validation\Validator;
 use Locale;
 
 require_once __DIR__ . '/stubs.php';
@@ -2668,6 +2670,21 @@ class ValidationTest extends TestCase
     }
 
     /**
+     * Test isArray
+     *
+     * @return void
+     */
+    public function testIsArray()
+    {
+        $this->assertTrue(Validation::isArray([]));
+        $this->assertTrue(Validation::isArray([1,2,3]));
+        $this->assertTrue(Validation::isArray(['key'=>'value']));
+        $this->assertFalse(Validation::isArray('[1,2,3]'));
+        $this->assertFalse(Validation::isArray(new Collection([])));
+        $this->assertFalse(Validation::isArray(10));
+    }
+
+    /**
      * Test isInteger
      *
      * @return void