Skip to content

Commit

Permalink
Allow using flag for normalization.
Browse files Browse the repository at this point in the history
  • Loading branch information
serge-kvashnin committed Apr 4, 2024
1 parent c2249ed commit 190fbb0
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 4 deletions.
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -718,18 +718,23 @@ $validator = new Validator($yourAdapter);

[**Flag**](./src/Rule/Flag.php)

- **Purpose**: Enforces that a value is either `true` or `false` (a boolean flag).
- **Purpose**: Enforces that a value is either `true` or `false` (a boolean flag)
and [normalizes](#accessing-normalized-data) it if necessary.
- **Options**:
- `value` (boolean): Specifies whether the rule requires the value to be `true` or `false`.
- `value` (boolean, default `null`): Enforces a specific value for the flag (true or false). Defaults to allowing
both `true` and `false`.
- **Examples**:
```php
use Norvica\Validation\Rule\Flag;

// normalized result will contain the boolean value (`true` or `false`)
$rule = new Flag();

// ensure value is `false`
$rule = new Flag(value: false);

// ensure value is `true`
$rule = new Flag(value: false);
$rule = new Flag(value: true);
```

[**Hostname**](./src/Rule/Hostname.php)
Expand Down
2 changes: 1 addition & 1 deletion src/Rule/Flag.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
readonly class Flag implements Rule, Normalizable
{
public function __construct(
public bool $value,
public bool|null $value = null,
) {
}

Expand Down
5 changes: 5 additions & 0 deletions src/Validation/FlagValidation.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ final class FlagValidation
{
public function __invoke(bool $value, Flag $rule): void
{
// both `true` and `false` are allowed
if ($rule->value === null) {
return;
}

if ($value !== $rule->value) {
$parameter = $rule->value ? 'true' : 'false';

Expand Down
6 changes: 6 additions & 0 deletions tests/Single/FlagTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,10 @@ public function testOffInvalid(mixed $value): void
{
$this->assertInvalid($value, new Flag(false));
}

public function testAnyBoolean(): void
{
$this->assertValid(true, new Flag());
$this->assertValid(false, new Flag());
}
}

0 comments on commit 190fbb0

Please sign in to comment.