Skip to content

Commit

Permalink
Adding a validation method to validate the count of a value
Browse files Browse the repository at this point in the history
  • Loading branch information
Florian Krämer committed Apr 27, 2016
1 parent 21012cc commit f055942
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/Validation/Validation.php
Expand Up @@ -215,6 +215,35 @@ 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 $check2 The expected count value.
* @return bool Success
*/
public static function count($check1, $operator, $expectedCount)
{
if (is_array($check1) || $check1 instanceof \Countable) {
$count = count($check1);
} elseif (is_string($check1)) {
$count = mb_strlen($check1);
} elseif (is_int($check1)) {
$count = $check1;
}

if (!$count) {
return false;
}

return self::comparison($count, $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 count
*
* @return void
*/
public function testCount()
{
$array = ['cake', 'php'];
$this->assertTrue(Validation::count($array, '==', 2));
$this->assertFalse(Validation::count($array, '>', 3));
$this->assertFalse(Validation::count($array, '<', 1));

$string = 'cakephp';
$this->assertTrue(Validation::count($string, '==', 7));
$this->assertFalse(Validation::count($string, '>', 8));
$this->assertFalse(Validation::count($string, '<', 1));

$int = 7;
$this->assertTrue(Validation::count($int, '==', 7));
$this->assertFalse(Validation::count($int, '>', 8));
$this->assertFalse(Validation::count($int, '<', 1));
}
}

0 comments on commit f055942

Please sign in to comment.