Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
e183b35
feat: added NotBlank rule documentation
andrepimpao Aug 8, 2023
498f1a9
chore: small README improvement
andrepimpao Aug 8, 2023
e705a79
feat: added GreaterThan rule documentation
andrepimpao Aug 8, 2023
2d0a49a
chore: more specific allowed value types for constraint
andrepimpao Aug 8, 2023
8d20093
feat: added GreaterThanOrEqual rule documentation
andrepimpao Aug 8, 2023
51f8b03
feat: added LessThan rule documentation
andrepimpao Aug 8, 2023
869694b
feat: added LessThanOrEqual rule documentation
andrepimpao Aug 8, 2023
a22bd34
fix: using wrong basic usage rule
andrepimpao Aug 8, 2023
c922cd7
feat: added Range rule documentation
andrepimpao Aug 8, 2023
50087e2
feat: added All rule documentation
andrepimpao Aug 8, 2023
c22e8c3
chore: small All documentation improvements
andrepimpao Aug 8, 2023
7619714
chore: small ocd
andrepimpao Aug 9, 2023
42178c6
feat: added Choice rule documentation
andrepimpao Aug 9, 2023
ce94e3c
chore: improved documentation rules data
andrepimpao Aug 9, 2023
205d5c0
chore: improved All rule message option example
andrepimpao Aug 9, 2023
dccdd98
chore: improved All rule message option example (again)
andrepimpao Aug 9, 2023
9aab4a9
chore: changed rules file names to force order
andrepimpao Aug 9, 2023
6775eed
chore: updated rules page with complete list
andrepimpao Aug 9, 2023
6154838
chore: fixed rule sections names
andrepimpao Aug 9, 2023
f564562
chore: updated usage, methods and custom exception messages sections
andrepimpao Aug 9, 2023
1d4d21e
chore: some text improvements
andrepimpao Aug 9, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,13 @@ use ProgrammatorDev\YetAnotherPhpValidator\Validator;
// Do this...
$validator = Validator::notBlank()->greaterThanOrEqual(18);

// ...or this...
// Or this...
$validator = new Validator(
new Rule\NotBlank(),
new Rule\GreaterThanOrEqual(18)
);

// ...and validate with these:
// Validate with these:
$validator->validate(16); // returns bool: false
$validator->assert(16, 'Age'); // throws exception: The "Age" value should be greater than or equal to "18", "16" given.
```
Expand Down
157 changes: 132 additions & 25 deletions docs/02-usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,22 @@
- Usage
- Fluent
- Dependency Injection
- Validation
- Methods
- assert
- validate
- getRules
- addRule
- Exception Handling
- Custom Exception Messages

## Usage

This library allows you to use validate data in two different ways:
- In a fluent way, making use of magic methods. The goal is to be able to create a set of rules with minimum setup;
- In a traditional way, making use of dependency injection. You may not like the fluent approach, and prefer to work this way.

Both should work exactly the same.

### Fluent

```php
Expand Down Expand Up @@ -40,18 +50,116 @@ use ProgrammatorDev\YetAnotherPhpValidator\Validator;
*/
function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem): float
{
(new Validator(new Rule\Range(-90, 90)))
->assert($latitude, 'Latitude');
(new Validator(new Rule\Range(-180, 180)))
->assert($longitude, 'Longitude');
(new Validator(new Rule\NotBlank(), new Rule\Choice(['METRIC', 'IMPERIAL'])))
->assert($unitSystem, 'Unit System');
(new Validator(new Rule\Range(-90, 90)))->assert($latitude, 'Latitude');
(new Validator(new Rule\Range(-180, 180)))->assert($longitude, 'Longitude');
(new Validator(new Rule\NotBlank(), new Rule\Choice(['METRIC', 'IMPERIAL'])))->assert($unitSystem, 'Unit System');

// ...
}
```

A `addRule` method is also available that may be useful for conditional rules:
## Methods

### `assert`

This method throws a `ValidationException` when a rule fails, otherwise nothing is returned.

```php
/**
* @throws ValidationException
*/
assert(mixed $value, string $name): void;
```

An example on how to handle an exception:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem): float
{
Validator::range(-90, 90)->assert($latitude, 'Latitude');
Validator::range(-180, 180)->assert($longitude, 'Longitude');
Validator::notBlank()->choice(['METRIC', 'IMPERIAL'])->assert($unitSystem, 'Unit System');

// ...
}

try {
getWeatherTemperature(latitude: 100, longitude: 50, unitSystem: 'METRIC');
}
catch (ValidationException $exception) {
echo $exception->getMessage(); // The "Latitude" value should be between "-90" and "90", "100" given.
}
```

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> Check the [Usage](#usage) section for more information.

### `validate`

This method always returns a `bool` when a rule fails, useful for conditions.

```php
validate(mixed $value): bool
```

An example:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

if (!Validator::range(-90, 90)->validate($latitude)) {
// Do something...
}
```

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> Check the [Usage](#usage) section for more information.

### `getRules`

Returns an array with the defined set of rules.

```php
/**
* @returns RuleInterface[]
*/
getRules(): array
```

An example:

```php
use ProgrammatorDev\YetAnotherPhpValidator\Rule;
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

$validator = new Validator(new Rule\GreaterThanOrEqual(0), new Rule\LessThanOrEqual(100));

print_r($validator->getRules());

// Array (
// [0] => ProgrammatorDev\YetAnotherPhpValidator\Rule\GreaterThanOrEqual Object
// [1] => ProgrammatorDev\YetAnotherPhpValidator\Rule\LessThanOrEqual Object
// )
```

> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> Check the [Usage](#usage) section for more information.

### `addRule`

Adds a rule to a set of rules. May be useful for conditional validations.

```php
addRule(RuleInterface $rule): self
```

An example:

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

## Validation
> **Note**
> The example only shows one usage approach, but both Fluent and Dependency Injection usage approaches should work the same.
> Check the [Usage](#usage) section for more information.

### `assert`
## Exception Handling

```php
use ProgrammatorDev\YetAnotherPhpValidator\Exception\ValidationException;
use ProgrammatorDev\YetAnotherPhpValidator\Validator;
## Custom Exception Messages

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

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

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

```php
use ProgrammatorDev\YetAnotherPhpValidator\Validator;

if (!Validator::range(-90, 90)->validate($latitude)) {
// do something...
}
Validator::choice(
constraints: ['red', 'green', 'blue'],
message: '"{{ value }}" is not a valid {{ name }}! You must select one of {{ constraints }}.'
)->assert('yellow', 'color');

// "yellow" is not a valid color! You must select one of [red, green, blue].
```
42 changes: 0 additions & 42 deletions docs/03-rules-notblank.md

This file was deleted.

36 changes: 24 additions & 12 deletions docs/03-rules.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,26 @@
# Rules

- Basic Constraints
- NotBlank
- Comparison Constraints
- LessThan
- LessThanOrEqual
- GreaterThan
- GreaterThanOrEqual
- Range
- Choice Constraints
- Choice
- Other Constraints
- All
- [Basic Rules](#basic-rules)
- [Comparison Rules](#comparison-rules)
- [Choice Rules](#choice-rules)
- [Array Rules](#array-rules)

## Basic Rules

- [NotBlank](03x-rules-not-blank.md)

## Comparison Rules

- [GreaterThan](03x-rules-greater-than.md)
- [GreaterThanOrEqual](03x-rules-greater-than-or-equal.md)
- [LessThan](03x-rules-less-than.md)
- [LessThanOrEqual](03x-rules-less-than-or-equal.md)
- [Range](03x-rules-range.md)

## Choice Rules

- [Choice](03x-rules-choice.md)

## Array Rules

- [All](03x-rules-all.md)
59 changes: 59 additions & 0 deletions docs/03x-rules-all.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
## All

Validates every element of an `array` with a given set of rules.

```php
/**
* @var RuleInterface[] $constraints
*/
All(
array $constraints,
string $message = 'At "{{ key }}": {{ message }}'
);
```

## Basic Usage

```php
// One rule per array element
Validator::all([Validator::notBlank(), Validator::greaterThan(1), Validator::lessThan(10)])->validate([4, 5, 6]); // true
Validator::all([Validator::notBlank(), Validator::greaterThan(1), Validator::lessThan(10)])->validate([4, 5, 20]); // false

// Multiple rules per array element
Validator::all([Validator::notBlank()->greaterThan(1)->lessThan(10)])->validate([4, 5, 6]); // true
```

> **Note**
> An `UnexpectedValueException` will be thrown if a `constraints` element does not implement a `RuleInterface`.

> **Note**
> An `UnexpectedValueException` will be thrown when value to be validated is not an `array`.

## Options

### `constraints`

type: `array` `required`

Collection of rules, or validators, to validate each element of an `array`.
Each element must implement a `RuleInterface`, so it is possible to use a single rule or a full validator set of rules.

### `message`

type: `string` default: `At "{{ key }}": {{ message }}`

Message that will be shown if at least one element of an array is invalid according to the given `constraints`.

```php
Validator::all([Validator::notBlank()])->assert(['red', 'green', ''], 'Test');
// Throws: At "2": The "Test" value should not be blank, "" given.
```

The following parameters are available:

| Parameter | Description |
|-----------------|-----------------------------------------------|
| `{{ value }}` | The current invalid value |
| `{{ name }}` | Name of the value being validated |
| `{{ key }}` | The array key of the invalid array element |
| `{{ message }}` | The rule message of the invalid array element |
Loading