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 */
4151function 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
57165use 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
95199use 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```
0 commit comments