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] > [!IMPORTANT]
> This coercion is only applies for `Ruleset->GET()`. `Ruleset->POST()` will enforce the real `null` value since it's JSON > 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()` ## `min()`
```php ```php
Rules->min(?int = null); Rules->min(?int = null);

View file

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