diff --git a/src/Rule/Length.php b/src/Rule/Length.php new file mode 100644 index 0000000..b7acce6 --- /dev/null +++ b/src/Rule/Length.php @@ -0,0 +1,55 @@ +length = $length; + $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 + { + return strlen($v) == $this->length; + } + + /** + * 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 + { + return $this->message?:"'${$v}' is supposed to be exactly ".$this->length." characters long"; + } +} \ No newline at end of file diff --git a/tests/Rule/LengthTest.php b/tests/Rule/LengthTest.php new file mode 100644 index 0000000..9570def --- /dev/null +++ b/tests/Rule/LengthTest.php @@ -0,0 +1,23 @@ +assertTrue($ruleFirst->validate("test")); + $this->assertFalse($ruleFirst->validate("test message")); + $this->assertEquals("Custom message",$ruleSecond->getMessage("test")); + $this->expectException(InvalidArgumentException::class); + + $ruleThird = new Length(-1); + } +} \ No newline at end of file