/** * Add a validation rule to ensure that a field is an array containing at most * the specified amount of elements * * @param string $field The field you want to apply the rule to. * @param int $count The number maximum amount of elements the field should have * @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. * @see \Cake\Validation\Validation::numElements() * @return $this */ public function hasAtMost($field, $count, $message = null, $when = null) { $extra = array_filter(['on' => $when, 'message' => $message]); return $this->add($field, 'hasAtMost', $extra + ['rule' => function ($value) use($count) { if (is_array($value) && isset($value['_ids'])) { $value = $value['_ids']; } return Validation::numElements($value, '<=', $count); }]); }
/** * 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)); }