Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update max length algo to work with file and array type #12

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
25 changes: 24 additions & 1 deletion src/Rules/MaxLengthRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down