diff --git a/src/Rule/ContainsNumericCharacters.php b/src/Rule/ContainsNumericCharacters.php new file mode 100644 index 0000000..eb5cd32 --- /dev/null +++ b/src/Rule/ContainsNumericCharacters.php @@ -0,0 +1,81 @@ +numberCharacters = $numberCharacters; + $this->strict = $strict; + $this->message = $message; + } + + /** + * Validates a value according to this rule and returns if it is valid or not + * @param mixed $v + * @return bool true if valid, otherwise false + */ + public function validate($v): bool + { + if($this->strict){ + return $this->countDigits($v)<=$this->numberCharacters; + } + return $this->countDigits($v)>=$this->numberCharacters; + + } + + /** + * Returns the message to be used in case the validation did not pass + * @param mixed $v the value that did not pass the validation + * @return string + */ + public function getMessage($v): string + { + if($this->message){ + return $this->message; + } + if($this->strict){ + return "Number of numeric characters exceeds ".${$this->numberCharacters}; + } + return "Number of numeric characters should exceed ".${$this->numberCharacters}; + } + + /** + * @param string $str + * @return int + */ + private function countDigits(string $str) + { + return preg_match_all( "/[0-9]/", $str )?:0; + } +} \ No newline at end of file diff --git a/tests/Rule/ContainsNumericCharactersTest.php b/tests/Rule/ContainsNumericCharactersTest.php new file mode 100644 index 0000000..d77f30d --- /dev/null +++ b/tests/Rule/ContainsNumericCharactersTest.php @@ -0,0 +1,22 @@ +assertTrue($ruleFirst->validate("test string 1")); + $this->assertFalse($ruleFirst->validate("test string 12")); + $this->assertFalse($ruleSecond->validate('test string')); + $this->assertTrue($ruleSecond->validate('test string 12')); + $this->assertEquals( "Custom Message", $ruleThird->getMessage("test string")); + $this->expectException(InvalidArgumentException::class); + $ruleForth = new ContainsNumericCharacters(-1,true); + } +} \ No newline at end of file