From c70a46568ec1fef8ab01e95965a8d5bb7cabb90d Mon Sep 17 00:00:00 2001 From: Victor Westerlund Date: Wed, 29 Nov 2023 06:54:32 +0100 Subject: [PATCH] feat: add `default()` rule for undefiend properties in scope (#6) * feat: add default() rule * feat(doc): add default() to README --- README.md | 6 ++++++ src/Rules.php | 18 ++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b4df7a1..9e7fe39 100644 --- a/README.md +++ b/README.md @@ -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); diff --git a/src/Rules.php b/src/Rules.php index 56d1d74..b12e0e2 100644 --- a/src/Rules.php +++ b/src/Rules.php @@ -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; }