From 45abd30747562d10a25fe0763dab8913cf8b5322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=CC=81=20Pimpa=CC=83o?= Date: Thu, 21 Mar 2024 10:52:08 +0000 Subject: [PATCH 1/2] docs: removed dependency injection examples --- README.md | 12 +--- docs/02-usage.md | 129 +++++----------------------------------- docs/04-custom-rules.md | 31 +++++----- 3 files changed, 32 insertions(+), 140 deletions(-) diff --git a/README.md b/README.md index b6b8096..3505b6b 100644 --- a/README.md +++ b/README.md @@ -39,16 +39,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. ``` @@ -56,7 +50,7 @@ $validator->assert(16, 'age'); // throws exception: The age value should be grea ## 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) diff --git a/docs/02-usage.md b/docs/02-usage.md index 24c6c52..3b7b287 100644 --- a/docs/02-usage.md +++ b/docs/02-usage.md @@ -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; @@ -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` @@ -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. @@ -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. @@ -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. @@ -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 } ``` @@ -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(); } ``` @@ -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"]. ``` \ No newline at end of file diff --git a/docs/04-custom-rules.md b/docs/04-custom-rules.md index b2833bb..6e13c0e 100644 --- a/docs/04-custom-rules.md +++ b/docs/04-custom-rules.md @@ -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 } } ``` @@ -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( @@ -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 @@ -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 { @@ -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'); ``` \ No newline at end of file From 65f46a3b7e6d53b76ce4439b1ea203a2ce60d9fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andre=CC=81=20Pimpa=CC=83o?= Date: Thu, 21 Mar 2024 10:55:04 +0000 Subject: [PATCH 2/2] docs: removed dependency injection examples from get started --- docs/01-get-started.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/docs/01-get-started.md b/docs/01-get-started.md index 6c9afae..50601d7 100644 --- a/docs/01-get-started.md +++ b/docs/01-get-started.md @@ -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. ``` \ No newline at end of file