Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding a validation method to validate the count of a value #8716

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Validation/Validation.php
Expand Up @@ -215,6 +215,26 @@ public static function cc($check, $type = 'fast', $deep = false, $regex = null)
return false;
}

/**
* 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)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Keeping the var name $check would be nice for consistency with other methods in class.

{
if (!is_array($check1) || $check1 instanceof \Countable) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

! is needed before $check1 instanceof \Countable. Adding ArrayObject test might be nice.

return false;
}
return self::comparison(count($check1), $operator, $expectedCount);
}

/**
* Used to compare 2 numeric values.
*
Expand Down
23 changes: 23 additions & 0 deletions tests/TestCase/Validation/ValidationTest.php
Expand Up @@ -2762,4 +2762,27 @@ public function testUtf8Extended()
// 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));
}
}