Skip to content

Commit

Permalink
Create "Templated" rule
Browse files Browse the repository at this point in the history
Because of how the validation engine works, there's no reason to keep
adding templates to each rule. Instead, creating a single rule that
handles templating rules will simplify the library greatly and shrink
the `Rule` interface.

Personally, I think this API is much more straightforward than the
`setTemplate()` method, as it's way more explicit which rule is being
templated.
  • Loading branch information
henriquemoody committed Dec 26, 2024
1 parent 634a155 commit 1d1da7f
Show file tree
Hide file tree
Showing 25 changed files with 234 additions and 166 deletions.
7 changes: 4 additions & 3 deletions bin/create-mixin
Original file line number Diff line number Diff line change
Expand Up @@ -171,17 +171,18 @@ function overwriteFile(string $content, string $basename): void
'PropertyExists',
'PropertyOptional',
'Attributes',
'Templated',
];

$mixins = [
['Key', 'key', [], $structureRelatedRules],
['Length', 'length', $numberRelatedRules, []],
['Max', 'max', $numberRelatedRules, []],
['Min', 'min', $numberRelatedRules, []],
['Not', 'not', [], ['Not', 'NotEmpty', 'NotBlank', 'NotEmoji', 'NotUndef', 'NotOptional', 'NullOr', 'UndefOr', 'Optional', 'Attributes']],
['NullOr', 'nullOr', [], ['Nullable', 'NullOr', 'Optional', 'NotOptional', 'NotUndef', 'UndefOr']],
['Not', 'not', [], ['Not', 'NotEmpty', 'NotBlank', 'NotEmoji', 'NotUndef', 'NotOptional', 'NullOr', 'UndefOr', 'Optional', 'Attributes', 'Templated']],
['NullOr', 'nullOr', [], ['Nullable', 'NullOr', 'Optional', 'NotOptional', 'NotUndef', 'UndefOr', 'Templated']],
['Property', 'property', [], $structureRelatedRules],
['UndefOr', 'undefOr', [], ['Nullable', 'NullOr', 'NotOptional', 'NotUndef', 'Optional', 'UndefOr', 'Attributes']],
['UndefOr', 'undefOr', [], ['Nullable', 'NullOr', 'NotOptional', 'NotUndef', 'Optional', 'UndefOr', 'Attributes', 'Templated']],
['', null, [], []],
];

Expand Down
12 changes: 12 additions & 0 deletions docs/09-list-of-rules-by-category.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,21 @@

- [AllOf](rules/AllOf.md)
- [AnyOf](rules/AnyOf.md)
- [Circuit](rules/Circuit.md)
- [NoneOf](rules/NoneOf.md)
- [OneOf](rules/OneOf.md)

## Conditions

- [Circuit](rules/Circuit.md)
- [Not](rules/Not.md)
- [When](rules/When.md)

## Core

- [Not](rules/Not.md)
- [Templated](rules/Templated.md)

## Date and Time

- [Date](rules/Date.md)
Expand Down Expand Up @@ -155,12 +162,14 @@
- [NotBlank](rules/NotBlank.md)
- [NotEmpty](rules/NotEmpty.md)
- [NotUndef](rules/NotUndef.md)
- [Templated](rules/Templated.md)

## Nesting

- [AllOf](rules/AllOf.md)
- [AnyOf](rules/AnyOf.md)
- [Call](rules/Call.md)
- [Circuit](rules/Circuit.md)
- [Each](rules/Each.md)
- [Key](rules/Key.md)
- [KeySet](rules/KeySet.md)
Expand Down Expand Up @@ -254,6 +263,7 @@
- [Property](rules/Property.md)
- [PropertyExists](rules/PropertyExists.md)
- [PropertyOptional](rules/PropertyOptional.md)
- [Templated](rules/Templated.md)

## Transformations

Expand Down Expand Up @@ -309,6 +319,7 @@
- [CallableType](rules/CallableType.md)
- [Callback](rules/Callback.md)
- [Charset](rules/Charset.md)
- [Circuit](rules/Circuit.md)
- [Cnh](rules/Cnh.md)
- [Cnpj](rules/Cnpj.md)
- [Consonant](rules/Consonant.md)
Expand Down Expand Up @@ -431,6 +442,7 @@
- [SubdivisionCode](rules/SubdivisionCode.md)
- [Subset](rules/Subset.md)
- [SymbolicLink](rules/SymbolicLink.md)
- [Templated](rules/Templated.md)
- [Time](rules/Time.md)
- [Tld](rules/Tld.md)
- [TrueVal](rules/TrueVal.md)
Expand Down
1 change: 1 addition & 0 deletions docs/rules/Attributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,4 @@ See also:
- [Property](Property.md)
- [PropertyExists](PropertyExists.md)
- [PropertyOptional](PropertyOptional.md)
- [Templated](Templated.md)
2 changes: 2 additions & 0 deletions docs/rules/Not.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Each other validation has custom messages for negated rules.

## Categorization

- Core
- Conditions
- Nesting

Expand All @@ -41,3 +42,4 @@ Each other validation has custom messages for negated rules.
See also:

- [NoneOf](NoneOf.md)
- [Templated](Templated.md)
49 changes: 49 additions & 0 deletions docs/rules/Templated.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Templated

- `Templated(Rule $rule, string $template)`
- `Templated(Rule $rule, string $template, array<string, mixed> $parameters)`

Defines a rule with a custom message template.

```php
v::templated(v::email(), 'You must provide a valid email to signup')->assert('not an email');
// Message: You must provide a valid email to signup

v::templated(
v::notEmpty(),
'The author of the page {{title}} is empty, please fill it up.',
['title' => 'Feature Guide']
)->assert('');
// Message: The author of the page "Feature Guide" is empty, please fill it up.
```

This rule can be also useful when you're using [Attributes](Attributes.md) and want a custom template for a specific property.

## Templates

This rule does not have any templates, as you must define the templates yourself.

## Template placeholders

| Placeholder | Description |
|-------------|------------------------------------------------------------------|
| `name` | The validated input or the custom validator name (if specified). |


## Categorization

- Core
- Structures
- Miscellaneous

## Changelog

| Version | Description |
|--------:|-------------|
| 3.0.0 | Created |

***
See also:

- [Attributes](Attributes.md)
- [Not](Not.md)
5 changes: 5 additions & 0 deletions library/Mixins/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,11 @@ public static function subset(array $superset): Chain;

public static function symbolicLink(): Chain;

/**
* @param array<string, mixed> $parameters
*/
public static function templated(Rule $rule, string $template, array $parameters = []): Chain;

public static function time(string $format = 'H:i:s'): Chain;

public static function tld(): Chain;
Expand Down
5 changes: 5 additions & 0 deletions library/Mixins/Chain.php
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,11 @@ public function subset(array $superset): Chain;

public function symbolicLink(): Chain;

/**
* @param array<string, mixed> $parameters
*/
public function templated(Rule $rule, string $template, array $parameters = []): Chain;

public function time(string $format = 'H:i:s'): Chain;

public function tld(): Chain;
Expand Down
15 changes: 10 additions & 5 deletions library/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,13 @@ final class Result

public readonly ?string $name;

public readonly string $template;

/** @param array<string, mixed> $parameters */
public function __construct(
public readonly bool $isValid,
public readonly mixed $input,
public readonly Rule $rule,
public readonly array $parameters = [],
string $template = Rule::TEMPLATE_STANDARD,
public readonly string $template = Rule::TEMPLATE_STANDARD,
public readonly Mode $mode = Mode::DEFAULT,
?string $name = null,
?string $id = null,
Expand All @@ -44,7 +42,6 @@ public function __construct(
Result ...$children,
) {
$this->name = $rule->getName() ?? $name;
$this->template = $rule->getTemplate() ?? $template;
$this->id = $id ?? lcfirst(substr((string) strrchr($rule::class, '\\'), 1));
$this->children = $children;
}
Expand Down Expand Up @@ -97,6 +94,12 @@ public function withTemplate(string $template): self
return $this->clone(template: $template);
}

/** @param array<string, mixed> $parameters */
public function withExtraParameters(array $parameters): self
{
return $this->clone(parameters: $parameters + $this->parameters);
}

public function withId(string $id): self
{
if ($this->unchangeableId) {
Expand Down Expand Up @@ -190,11 +193,13 @@ public function allowsAdjacent(): bool
}

/**
* @param array<string, mixed> $parameters
* @param array<Result>|null $children
*/
private function clone(
?bool $isValid = null,
mixed $input = null,
?array $parameters = null,
?string $template = null,
?Mode $mode = null,
?string $name = null,
Expand All @@ -207,7 +212,7 @@ private function clone(
$isValid ?? $this->isValid,
$input ?? $this->input,
$this->rule,
$this->parameters,
$parameters ?? $this->parameters,
$template ?? $this->template,
$mode ?? $this->mode,
$name ?? $this->name,
Expand Down
4 changes: 0 additions & 4 deletions library/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,4 @@ public function evaluate(mixed $input): Result;
public function getName(): ?string;

public function setName(string $name): static;

public function getTemplate(): ?string;

public function setTemplate(string $template): static;
}
4 changes: 0 additions & 4 deletions library/Rules/Core/Binder.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@ public function evaluate(mixed $input): Result
$this->bound->setName($this->source->getName());
}

if ($this->source->getTemplate() !== null && $this->bound->getTemplate() === null) {
$this->bound->setTemplate($this->source->getTemplate());
}

return $this->bound->evaluate($input);
}
}
14 changes: 0 additions & 14 deletions library/Rules/Core/Composite.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ abstract class Composite implements Rule

private ?string $name = null;

private ?string $template = null;

public function __construct(Rule $rule1, Rule $rule2, Rule ...$rules)
{
$this->rules = array_merge([$rule1, $rule2], $rules);
Expand Down Expand Up @@ -55,16 +53,4 @@ public function getName(): ?string
{
return $this->name;
}

public function setTemplate(string $template): static
{
$this->template = $template;

return $this;
}

public function getTemplate(): ?string
{
return $this->template;
}
}
10 changes: 10 additions & 0 deletions library/Rules/Core/Reducer.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,21 @@

use Respect\Validation\Rule;
use Respect\Validation\Rules\AllOf;
use Respect\Validation\Rules\Templated;

final class Reducer extends Wrapper
{
public function __construct(Rule $rule1, Rule ...$rules)
{
parent::__construct($rules === [] ? $rule1 : new AllOf($rule1, ...$rules));
}

public function withTemplate(?string $template): self
{
if ($template === null) {
return $this;
}

return new self(new Templated($this->rule, $template));
}
}
14 changes: 0 additions & 14 deletions library/Rules/Core/Standard.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,6 @@ abstract class Standard implements Rule

private ?string $name = null;

private ?string $template = null;

public function getName(): ?string
{
return $this->name;
Expand All @@ -31,16 +29,4 @@ public function setName(string $name): static

return $this;
}

public function getTemplate(): ?string
{
return $this->template;
}

public function setTemplate(string $template): static
{
$this->template = $template;

return $this;
}
}
12 changes: 0 additions & 12 deletions library/Rules/Core/Wrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,6 @@ public function setName(string $name): static
return $this;
}

public function getTemplate(): ?string
{
return $this->rule->getTemplate();
}

public function setTemplate(string $template): static
{
$this->rule->setTemplate($template);

return $this;
}

public function getRule(): Rule
{
return $this->rule;
Expand Down
38 changes: 38 additions & 0 deletions library/Rules/Templated.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* Copyright (c) Alexandre Gomes Gaigalas <[email protected]>
* SPDX-License-Identifier: MIT
*/

declare(strict_types=1);

namespace Respect\Validation\Rules;

use Attribute;
use Respect\Validation\Result;
use Respect\Validation\Rule;
use Respect\Validation\Rules\Core\Wrapper;

#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final class Templated extends Wrapper
{
/** @param array<string, mixed> $parameters */
public function __construct(
Rule $rule,
private readonly string $template,
private readonly array $parameters = []
) {
parent::__construct($rule);
}

public function evaluate(mixed $input): Result
{
$result = $this->rule->evaluate($input);
if ($result->hasCustomTemplate()) {
return $result;
}

return $result->withTemplate($this->template)->withExtraParameters($this->parameters);
}
}
3 changes: 1 addition & 2 deletions library/Rules/When.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ public function __construct(
?Rule $else = null
) {
if ($else === null) {
$else = new AlwaysInvalid();
$else->setTemplate(AlwaysInvalid::TEMPLATE_SIMPLE);
$else = new Templated(new AlwaysInvalid(), AlwaysInvalid::TEMPLATE_SIMPLE);
}

$this->else = $else;
Expand Down
Loading

0 comments on commit 1d1da7f

Please sign in to comment.