Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit 5d10217

Browse files
authored
Merge pull request #20 from programmatordev/YAPV-12-create-documentation
Create documentation (in progress)
2 parents b312608 + 1d4d21e commit 5d10217

13 files changed

+711
-90
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,13 @@ use ProgrammatorDev\YetAnotherPhpValidator\Validator;
3131
// Do this...
3232
$validator = Validator::notBlank()->greaterThanOrEqual(18);
3333

34-
// ...or this...
34+
// Or this...
3535
$validator = new Validator(
3636
new Rule\NotBlank(),
3737
new Rule\GreaterThanOrEqual(18)
3838
);
3939

40-
// ...and validate with these:
40+
// Validate with these:
4141
$validator->validate(16); // returns bool: false
4242
$validator->assert(16, 'Age'); // throws exception: The "Age" value should be greater than or equal to "18", "16" given.
4343
```

docs/02-usage.md

Lines changed: 132 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,22 @@
33
- Usage
44
- Fluent
55
- Dependency Injection
6-
- Validation
6+
- Methods
77
- assert
88
- validate
9+
- getRules
10+
- addRule
11+
- Exception Handling
12+
- Custom Exception Messages
913

1014
## Usage
1115

16+
This library allows you to use validate data in two different ways:
17+
- In a fluent way, making use of magic methods. The goal is to be able to create a set of rules with minimum setup;
18+
- In a traditional way, making use of dependency injection. You may not like the fluent approach, and prefer to work this way.
19+
20+
Both should work exactly the same.
21+
1222
### Fluent
1323

1424
```php
@@ -40,18 +50,116 @@ use ProgrammatorDev\YetAnotherPhpValidator\Validator;
4050
*/
4151
function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem): float
4252
{
43-
(new Validator(new Rule\Range(-90, 90)))
44-
->assert($latitude, 'Latitude');
45-
(new Validator(new Rule\Range(-180, 180)))
46-
->assert($longitude, 'Longitude');
47-
(new Validator(new Rule\NotBlank(), new Rule\Choice(['METRIC', 'IMPERIAL'])))
48-
->assert($unitSystem, 'Unit System');
53+
(new Validator(new Rule\Range(-90, 90)))->assert($latitude, 'Latitude');
54+
(new Validator(new Rule\Range(-180, 180)))->assert($longitude, 'Longitude');
55+
(new Validator(new Rule\NotBlank(), new Rule\Choice(['METRIC', 'IMPERIAL'])))->assert($unitSystem, 'Unit System');
4956

5057
// ...
5158
}
5259
```
5360

54-
A `addRule` method is also available that may be useful for conditional rules:
61+
## Methods
62+
63+
### `assert`
64+
65+
This method throws a `ValidationException` when a rule fails, otherwise nothing is returned.
66+
67+
```php
68+
/**
69+
* @throws ValidationException
70+
*/
71+
assert(mixed $value, string $name): void;
72+
```
73+
74+
An example on how to handle an exception:
75+
76+
```php
77+
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
78+
use ProgrammatorDev\YetAnotherPhpValidator\Validator;
79+
80+
function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem): float
81+
{
82+
Validator::range(-90, 90)->assert($latitude, 'Latitude');
83+
Validator::range(-180, 180)->assert($longitude, 'Longitude');
84+
Validator::notBlank()->choice(['METRIC', 'IMPERIAL'])->assert($unitSystem, 'Unit System');
85+
86+
// ...
87+
}
88+
89+
try {
90+
getWeatherTemperature(latitude: 100, longitude: 50, unitSystem: 'METRIC');
91+
}
92+
catch (ValidationException $exception) {
93+
echo $exception->getMessage(); // The "Latitude" value should be between "-90" and "90", "100" given.
94+
}
95+
```
96+
97+
> **Note**
98+
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
99+
> Check the [Usage](#usage) section for more information.
100+
101+
### `validate`
102+
103+
This method always returns a `bool` when a rule fails, useful for conditions.
104+
105+
```php
106+
validate(mixed $value): bool
107+
```
108+
109+
An example:
110+
111+
```php
112+
use ProgrammatorDev\YetAnotherPhpValidator\Validator;
113+
114+
if (!Validator::range(-90, 90)->validate($latitude)) {
115+
// Do something...
116+
}
117+
```
118+
119+
> **Note**
120+
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
121+
> Check the [Usage](#usage) section for more information.
122+
123+
### `getRules`
124+
125+
Returns an array with the defined set of rules.
126+
127+
```php
128+
/**
129+
* @returns RuleInterface[]
130+
*/
131+
getRules(): array
132+
```
133+
134+
An example:
135+
136+
```php
137+
use ProgrammatorDev\YetAnotherPhpValidator\Rule;
138+
use ProgrammatorDev\YetAnotherPhpValidator\Validator;
139+
140+
$validator = new Validator(new Rule\GreaterThanOrEqual(0), new Rule\LessThanOrEqual(100));
141+
142+
print_r($validator->getRules());
143+
144+
// Array (
145+
// [0] => ProgrammatorDev\YetAnotherPhpValidator\Rule\GreaterThanOrEqual Object
146+
// [1] => ProgrammatorDev\YetAnotherPhpValidator\Rule\LessThanOrEqual Object
147+
// )
148+
```
149+
150+
> **Note**
151+
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
152+
> Check the [Usage](#usage) section for more information.
153+
154+
### `addRule`
155+
156+
Adds a rule to a set of rules. May be useful for conditional validations.
157+
158+
```php
159+
addRule(RuleInterface $rule): self
160+
```
161+
162+
An example:
55163

56164
```php
57165
use ProgrammatorDev\YetAnotherPhpValidator\Rule;
@@ -71,30 +179,29 @@ function calculateDiscount(float $price, float $discount, string $type): float
71179
}
72180
```
73181

74-
## Validation
182+
> **Note**
183+
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
184+
> Check the [Usage](#usage) section for more information.
75185
76-
### `assert`
186+
## Exception Handling
77187

78-
```php
79-
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
80-
use ProgrammatorDev\YetAnotherPhpValidator\Validator;
188+
## Custom Exception Messages
81189

82-
// function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem)
190+
All rules have at least one error message that can be customized (some rules have more than one error message for different case scenarios).
83191

84-
try {
85-
getWeatherTemperature(100, 50, 'METRIC');
86-
}
87-
catch (ValidationException $exception) {
88-
echo $exception->getMessage(); // The "Latitude" value should be between "-90" and "90", "100" given.
89-
}
90-
```
192+
Every message has a list of dynamic parameters to help create an intuitive error text (like the invalid value, constraints, names, and others).
193+
To check what parameters and messages are available, look into the Options section in the page of a rule.
194+
Go to [Rules](03-rules.md) to see all available rules.
91195

92-
### `validate`
196+
The following example uses the [Choice](03x-rules-choice.md) rule with a custom error message:
93197

94198
```php
95199
use ProgrammatorDev\YetAnotherPhpValidator\Validator;
96200

97-
if (!Validator::range(-90, 90)->validate($latitude)) {
98-
// do something...
99-
}
201+
Validator::choice(
202+
constraints: ['red', 'green', 'blue'],
203+
message: '"{{ value }}" is not a valid {{ name }}! You must select one of {{ constraints }}.'
204+
)->assert('yellow', 'color');
205+
206+
// "yellow" is not a valid color! You must select one of [red, green, blue].
100207
```

docs/03-rules-notblank.md

Lines changed: 0 additions & 42 deletions
This file was deleted.

docs/03-rules.md

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,26 @@
11
# Rules
22

3-
- Basic Constraints
4-
- NotBlank
5-
- Comparison Constraints
6-
- LessThan
7-
- LessThanOrEqual
8-
- GreaterThan
9-
- GreaterThanOrEqual
10-
- Range
11-
- Choice Constraints
12-
- Choice
13-
- Other Constraints
14-
- All
3+
- [Basic Rules](#basic-rules)
4+
- [Comparison Rules](#comparison-rules)
5+
- [Choice Rules](#choice-rules)
6+
- [Array Rules](#array-rules)
7+
8+
## Basic Rules
9+
10+
- [NotBlank](03x-rules-not-blank.md)
11+
12+
## Comparison Rules
13+
14+
- [GreaterThan](03x-rules-greater-than.md)
15+
- [GreaterThanOrEqual](03x-rules-greater-than-or-equal.md)
16+
- [LessThan](03x-rules-less-than.md)
17+
- [LessThanOrEqual](03x-rules-less-than-or-equal.md)
18+
- [Range](03x-rules-range.md)
19+
20+
## Choice Rules
21+
22+
- [Choice](03x-rules-choice.md)
23+
24+
## Array Rules
25+
26+
- [All](03x-rules-all.md)

docs/03x-rules-all.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
## All
2+
3+
Validates every element of an `array` with a given set of rules.
4+
5+
```php
6+
/**
7+
* @var RuleInterface[] $constraints
8+
*/
9+
All(
10+
array $constraints,
11+
string $message = 'At "{{ key }}": {{ message }}'
12+
);
13+
```
14+
15+
## Basic Usage
16+
17+
```php
18+
// One rule per array element
19+
Validator::all([Validator::notBlank(), Validator::greaterThan(1), Validator::lessThan(10)])->validate([4, 5, 6]); // true
20+
Validator::all([Validator::notBlank(), Validator::greaterThan(1), Validator::lessThan(10)])->validate([4, 5, 20]); // false
21+
22+
// Multiple rules per array element
23+
Validator::all([Validator::notBlank()->greaterThan(1)->lessThan(10)])->validate([4, 5, 6]); // true
24+
```
25+
26+
> **Note**
27+
> An `UnexpectedValueException` will be thrown if a `constraints` element does not implement a `RuleInterface`.
28+
29+
> **Note**
30+
> An `UnexpectedValueException` will be thrown when value to be validated is not an `array`.
31+
32+
## Options
33+
34+
### `constraints`
35+
36+
type: `array` `required`
37+
38+
Collection of rules, or validators, to validate each element of an `array`.
39+
Each element must implement a `RuleInterface`, so it is possible to use a single rule or a full validator set of rules.
40+
41+
### `message`
42+
43+
type: `string` default: `At "{{ key }}": {{ message }}`
44+
45+
Message that will be shown if at least one element of an array is invalid according to the given `constraints`.
46+
47+
```php
48+
Validator::all([Validator::notBlank()])->assert(['red', 'green', ''], 'Test');
49+
// Throws: At "2": The "Test" value should not be blank, "" given.
50+
```
51+
52+
The following parameters are available:
53+
54+
| Parameter | Description |
55+
|-----------------|-----------------------------------------------|
56+
| `{{ value }}` | The current invalid value |
57+
| `{{ name }}` | Name of the value being validated |
58+
| `{{ key }}` | The array key of the invalid array element |
59+
| `{{ message }}` | The rule message of the invalid array element |

0 commit comments

Comments
 (0)