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
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
12 changes: 3 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,24 +39,18 @@ Simple usage looks like:
use ProgrammatorDev\Validator\Rule;
use ProgrammatorDev\Validator\Validator;

// Do this...
// do this...
$validator = Validator::notBlank()->greaterThanOrEqual(18);

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

// Validate with these:
// ...and 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.
```

## Documentation

- [Get Started](docs/01-get-started.md)
- [Usage](docs/02-usage.md)
- [How to Use](docs/02-usage.md)
- [Usage](docs/02-usage.md#usage)
- [Methods](docs/02-usage.md#methods)
- [Error Handling](docs/02-usage.md#error-handling)
Expand Down
10 changes: 2 additions & 8 deletions docs/01-get-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,10 @@ Simple usage looks like:
use ProgrammatorDev\Validator\Rule;
use ProgrammatorDev\Validator\Validator;

// Do this...
// do this...
$validator = Validator::notBlank()->greaterThanOrEqual(18);

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

// Validate with these:
// ...and 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.
```
129 changes: 14 additions & 115 deletions docs/02-usage.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,15 @@
# Using Yet Another PHP Validator

- [Usage](#usage)
- [Fluent](#fluent)
- [Dependency Injection](#dependency-injection)
- [Methods](#methods)
- [assert](#assert)
- [validate](#validate)
- [getRules](#getrules)
- [addRule](#addrule)
- [Error Handling](#error-handling)
- [Custom Error Messages](#custom-error-messages)

## Usage

This library allows you to 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
This library allows you to validate data with a set of rules with minimum setup:

```php
use ProgrammatorDev\Validator\Exception\ValidationException;
Expand All @@ -28,36 +18,16 @@ use ProgrammatorDev\Validator\Validator;
/**
* @throws ValidationException
*/
function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem): float
public function getWeather(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');
Validator::notBlank()->choice(['metric', 'imperial'])->assert($unitSystem, 'unit system');

// ...
}
```

### Dependency Injection

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

/**
* @throws ValidationException
*/
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');

// ...
}
```

## Methods

### `assert`
Expand All @@ -77,17 +47,17 @@ An example on how to handle an error:
use ProgrammatorDev\Validator\Exception\ValidationException;
use ProgrammatorDev\Validator\Validator;

function getWeatherTemperature(float $latitude, float $longitude, string $unitSystem): float
function getWeather(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');
Validator::notBlank()->choice(['metric', 'imperial'])->assert($unitSystem, 'unit system');

// ...
}

try {
getWeatherTemperature(latitude: 100, longitude: 50, unitSystem: 'METRIC');
getWeather(latitude: 100, longitude: 50, unitSystem: 'metric');
}
catch (ValidationException $exception) {
echo $exception->getMessage(); // The latitude value should be between -90 and 90, 100 given.
Expand All @@ -96,10 +66,6 @@ catch (ValidationException $exception) {
> [!NOTE]
> Check the [Error Handling](#error-handling) section for more information.

> [!NOTE]
> The example only shows one usage approach, but both Fluent and Dependency Injection 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.
Expand All @@ -114,77 +80,10 @@ An example:
use ProgrammatorDev\Validator\Validator;

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

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

### `getRules`

Returns an array with the defined set of rules.

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

An example:

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

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

print_r($validator->getRules());

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

> [!NOTE]
> The example only shows one usage approach, but both Fluent and Dependency Injection 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\Validator\Rule;
use ProgrammatorDev\Validator\Validator;

function calculateDiscount(float $price, float $discount, string $type): float
{
$discountValidator = new Validator(new GreaterThan(0));

if ($type === 'PERCENT') {
$discountValidator->addRule(new Rule\LessThanOrEqual(100));
}

$discountValidator->assert($discount, 'discount');

// ...
}
```

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

## Error Handling

When using the [`assert`](#assert) method, an exception is thrown when a rule fails.
Expand All @@ -199,16 +98,16 @@ use ProgrammatorDev\Validator\Validator;
try {
Validator::range(-90, 90)->assert($latitude, 'latitude');
Validator::range(-180, 180)->assert($longitude, 'longitude');
Validator::notBlank()->choice(['METRIC', 'IMPERIAL'])->assert($unitSystem, 'unit system');
Validator::notBlank()->choice(['metric', 'imperial'])->assert($unitSystem, 'unit system');
}
catch (Exception\RangeException $exception) {
// Do something when Range fails
// do something when Range fails
}
catch (Exception\NotBlankException $exception) {
// Do something when NotBlank fails
// do something when NotBlank fails
}
catch (Exception\ChoiceException $exception) {
// Do something when Choice fails
// do something when Choice fails
}
```

Expand All @@ -221,10 +120,10 @@ use ProgrammatorDev\Validator\Validator;
try {
Validator::range(-90, 90)->assert($latitude, 'latitude');
Validator::range(-180, 180)->assert($longitude, 'longitude');
Validator::notBlank()->choice(['METRIC', 'IMPERIAL'])->assert($unitSystem, 'unit system');
Validator::notBlank()->choice(['metric', 'imperial'])->assert($unitSystem, 'unit system');
}
catch (ValidationException $exception) {
// Do something when a rule fails
// do something when a rule fails
echo $exception->getMessage();
}
```
Expand Down Expand Up @@ -264,5 +163,5 @@ Validator::choice(
message: '{{ value }} is not a valid {{ name }}! You must select one of {{ constraints }}.'
)->assert('yellow', 'color');

// Throws: "yellow" is not a valid color! You must select one of ["red", "green", "blue"].
// throws: "yellow" is not a valid color! You must select one of ["red", "green", "blue"].
```
31 changes: 15 additions & 16 deletions docs/04-custom-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ use ProgrammatorDev\Validator\Rule\RuleInterface;

class CustomRule extends AbstractRule implements RuleInterface
{
public function assert(mixed $value, string $name): void
public function assert(mixed $value, ?string $name = null): void
{
// Do validation
// do validation
}
}
```
Expand All @@ -47,7 +47,7 @@ use My\Project\Exception\CustomRuleException;

class CustomRule extends AbstractRule implements RuleInterface
{
public function assert(mixed $value, string $name): void
public function assert(mixed $value, ?string $name = null): void
{
if ($value === 0) {
throw new CustomRuleException(
Expand All @@ -66,18 +66,13 @@ In the example above, a new custom rule was created that validates if the input
To use your new custom rule, simply do the following:

```php
// Fluent way, notice the rule() method
// notice the rule() method
$validator = Validator::rule(new CustomRule());
// With multiple rules
// with multiple rules
$validator = Validator::range(-10, 10)->rule(new CustomRule());

// Dependency injection way
$validator = new Validator(new CustomRule());
// With multiple rules
$validator = new Validator(new Range(-10, 10), new CustomRule());

$validator->assert(0, 'test'); // throws: The test value cannot be zero!
$validator->validate(0); // false
$validator->assert(0, 'test'); // throws: The test value cannot be zero!
```

## Message Template
Expand All @@ -88,15 +83,17 @@ This means that you can have dynamic content in your messages.
To make it work, just pass an associative array with the name and value of your parameters, and they will be available in the message:

```php
// Exception
// exception
class FavoriteException extends ValidationException {}
```

// Rule
```php
// rule
class Favorite extends AbstractRule implements RuleInterface
{
public function __construct(
private readonly string $favorite
)
private readonly string $favorite
) {}

public function assert(mixed $value, ?string $name = null): void
{
Expand All @@ -112,7 +109,9 @@ class Favorite extends AbstractRule implements RuleInterface
}
}
}
```

// Throws: My favorite animal is "cat", not "human"!
```php
// throws: My favorite animal is "cat", not "human"!
Validator::rule(new Favorite('cat'))->assert('human', 'animal');
```