Browse Source

Add Validator::array().

Deprecate Validator::isArray(). Closes #17072.
ADmad 3 years ago
parent
commit
bce7e0036c
2 changed files with 38 additions and 3 deletions
  1. 22 0
      src/Validation/Validator.php
  2. 16 3
      tests/TestCase/Validation/ValidatorTest.php

+ 22 - 0
src/Validation/Validator.php

@@ -2349,8 +2349,30 @@ class Validator implements ArrayAccess, IteratorAggregate, Countable
      * @see \Cake\Validation\Validation::isArray()
      * @return $this
      */
+    public function array(string $field, ?string $message = null, $when = null)
+    {
+        $extra = array_filter(['on' => $when, 'message' => $message]);
+
+        return $this->add($field, 'array', $extra + [
+            'rule' => 'isArray',
+        ]);
+    }
+
+    /**
+     * 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 callable|string|null $when Either 'create' or 'update' or a callable that returns
+     *   true when the validation rule should be applied.
+     * @see \Cake\Validation\Validation::isArray()
+     * @return $this
+     * @deprecated 4.5.0 Use Validator::array() instead.
+     */
     public function isArray(string $field, ?string $message = null, $when = null)
     {
+        deprecationWarning('`Validator::isArray()` is deprecated, use `Validator::array()` instead');
+
         $extra = array_filter(['on' => $when, 'message' => $message]);
 
         return $this->add($field, 'isArray', $extra + [

+ 16 - 3
tests/TestCase/Validation/ValidatorTest.php

@@ -2636,17 +2636,30 @@ class ValidatorTest extends TestCase
     }
 
     /**
-     * Tests the isArray proxy method
+     * Tests the array proxy method
      */
-    public function testIsArray(): void
+    public function testArray(): void
     {
         $validator = new Validator();
-        $validator->isArray('username');
+        $validator->array('username');
         $this->assertEmpty($validator->validate(['username' => [1, 2, 3]]));
         $this->assertNotEmpty($validator->validate(['username' => 'is not an array']));
     }
 
     /**
+     * Tests the isArray proxy method
+     */
+    public function testIsArray(): void
+    {
+        $this->deprecated(function () {
+            $validator = new Validator();
+            $validator->isArray('username');
+            $this->assertEmpty($validator->validate(['username' => [1, 2, 3]]));
+            $this->assertNotEmpty($validator->validate(['username' => 'is not an array']));
+        });
+    }
+
+    /**
      * Tests the scalar proxy method
      */
     public function testScalar(): void