From 266981e66bae66bbf9d3b08649dde1a3b55228c7 Mon Sep 17 00:00:00 2001 From: Kabirou ALASSANE Date: Wed, 22 Nov 2023 16:52:32 +0100 Subject: [PATCH] Update max length algo to work with file and array type --- README.md | 2 +- src/Rules/MaxLengthRule.php | 25 ++++++++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index fb7731f..d45e7a7 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,7 @@ PHPValidator provides a variety of predefined rules that you can use for data va - Validates that a field's value is not in a specified set. ```php - 'value' => 'not_in:["foo", "bar"]' + 'value' => 'not_in:foo,bar' ``` 20. **Required With Rule** - Requires the field to be present if another specified field is present. diff --git a/src/Rules/MaxLengthRule.php b/src/Rules/MaxLengthRule.php index a19723b..f574d43 100644 --- a/src/Rules/MaxLengthRule.php +++ b/src/Rules/MaxLengthRule.php @@ -50,7 +50,30 @@ public function passes(string $field, $value, array $data): bool $maxLength = $this->parameters[0] ?? 0; // Check if the value is a string and its length is within the specified maximum. - return is_string($value) && mb_strlen($value) <= $maxLength; + if (is_string($value)) { + $value = mb_strlen($value); + } + + if (is_array($value)) { + $value = count($value); + } + + if (is_file($value)) { + + if (isset($_FILES[$value]) && $_FILES[$value]["error"] == 0) { + // Get the file size in bytes + $size = $_FILES[$value]["size"]; + + // Convert bytes to kilobytes + $size_kb = $size / 1024; // kilobytes + + $value = $size_kb; + } + + return false; + } + + return $value <= $maxLength; } /**