From 1e17fe0f981890e0db2f5ae11d700aa8a378efe5 Mon Sep 17 00:00:00 2001 From: Thibault JUNIN Date: Wed, 12 Jun 2024 22:57:09 +0200 Subject: [PATCH] add array handling for length validation add php 8.3 to ci Signed-off-by: Thibault JUNIN --- .github/workflows/php.yml | 2 +- src/Validator.php | 11 +++++++++-- tests/SimpleTest.php | 11 +++++++++++ 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index f9360b1..77619e4 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -13,7 +13,7 @@ jobs: strategy: fail-fast: false matrix: - php: [ 8.1, 8.2 ] + php: [ 8.1, 8.2, 8.3 ] name: PHP ${{ matrix.php }} tests diff --git a/src/Validator.php b/src/Validator.php index ff498a4..61371ea 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -145,12 +145,19 @@ public function length(string $key, int $min, ?int $max = NULL): self return $this; } - if (strlen($value) < $min) { + $length = 0; + if (is_array($value)) { + $length = count($value); + } else { + $length = strlen($value); + } + + if ($length < $min) { $this->addError($key, ValidationRules::LENGTH, $min, $max); return $this; } - if ($max != NULL && strlen($value) > $max) { + if ($max != NULL && $length > $max) { $this->addError($key, ValidationRules::LENGTH, $min, $max); return $this; } diff --git a/tests/SimpleTest.php b/tests/SimpleTest.php index 80cd6bf..affc699 100644 --- a/tests/SimpleTest.php +++ b/tests/SimpleTest.php @@ -67,6 +67,17 @@ public function testLength() $this->assertCount(1, $validator->getErrors(), json_encode($validator->getErrors())); } + public function testLengthArray() + { + $validator = $this->createValidator(["abc" => ["a", "b", "c"]]); + $validator->length("abc", 2, 4); + $this->assertCount(0, $validator->getErrors(), json_encode($validator->getErrors())); + + $validator = $this->createValidator(["abc" => ["a", "b", "c", "d", "e", "f"]]); + $validator->length("abc", 2, 4); + $this->assertCount(1, $validator->getErrors(), json_encode($validator->getErrors())); + } + public function testDateTime() { $validator = $this->createValidator(["abc" => "2022-03-20 03:08:42"]);