feat: add default() rule for undefiend properties in scope (#6)

* feat: add default() rule

* feat(doc): add default() to README
This commit is contained in:
Victor Westerlund 2023-11-29 06:54:32 +01:00 committed by GitHub
parent 6583f87866
commit c70a46568e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 2 deletions

View file

@ -125,6 +125,12 @@ Any value that isn't an empty string will cause the `type()` rule to fail.
> [!IMPORTANT]
> This coercion is only applies for `Ruleset->GET()`. `Ruleset->POST()` will enforce the real `null` value since it's JSON
## `default()`
```php
Rules->default(mixed);
```
Set superglobal property to a defined default value if the property was not provided in superglobal scope
## `min()`
```php
Rules->min(?int = null);

View file

@ -24,6 +24,9 @@
public bool $required = false;
public ?Type $type = null;
private bool $default_enabled = false;
public mixed $default;
public ?int $min = null;
public ?int $max = null;
@ -76,6 +79,14 @@
return $this;
}
// Set a default value if property is not provided
public function default(mixed $value): self {
$this->default_enabled = true;
$this->default = $value;
return $this;
}
/*
# Eval methods
These methods are used to check conformity against set rules.
@ -124,8 +135,11 @@
return true;
}
// Property does not exist in scope, create nulled superglobal for it
$scope_data[$this->property] = null;
// Property does not exist in superglobal, create one with default value if enabled
if ($this->default_enabled) {
$scope_data[$this->property] = $this->default;
}
return false;
}