From b8290c91e5517739b46f2a19f83d2149a7552b3b Mon Sep 17 00:00:00 2001 From: Kabirou ALASSANE Date: Sun, 19 Nov 2023 16:10:57 +0100 Subject: [PATCH 1/6] Add custom validatation error message --- src/Validator.php | 11 +++++++++-- tests/Feature/ValidatorTest.php | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/Validator.php b/src/Validator.php index 3aa8a46..c4f5402 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -24,8 +24,12 @@ class Validator extends RulesMaped * * @param array $data Data to be validated. * @param array $rules Validation rules to apply. + * @param array $messages Validation rules messages to apply when failed. */ - public function __construct(private array $data, private array $rules) + public function __construct(private array $data, + private array $rules, + private array $messages = [] + ) { $this->validateConstructorInputs(); $this->validate(); @@ -112,7 +116,10 @@ protected function validate() protected function checkPasses(mixed $validator, string $field) { if (isset($this->data[$field]) && !$validator->passes($field, $this->data[$field], $this->data)) { - $this->addError($field, $validator->message()); + + $message = isset($this->messages[$field]) ? $this->messages[$field] : $validator->message(); + + $this->addError($field, $message); } } diff --git a/tests/Feature/ValidatorTest.php b/tests/Feature/ValidatorTest.php index 6a2b5c8..678fc8c 100644 --- a/tests/Feature/ValidatorTest.php +++ b/tests/Feature/ValidatorTest.php @@ -18,3 +18,17 @@ expect(fn () => new Validator(['name' => 'John'], ['name' => 'nonexistent'])) ->toThrow(ValidatorException::class, LangManager::getTranslation('validation.rule_not_found', ['ruleName' => 'nonexistent'])); }); + +it('validates rule with custom error message', function () { + + $errorMessage = "Je teste une règle custom"; + + $validator = new Validator( + ['field' => ''], + ['field' => 'required'], + ['field' => $errorMessage] + ); + expect($validator->isValid())->toBeFalse(); + + expect($validator->getErrors()['field'][0])->toBe($errorMessage); +}); \ No newline at end of file From 88ebc9a48416dc0090e02e9c432e21c8bb0a5bab Mon Sep 17 00:00:00 2001 From: Kabirou ALASSANE Date: Sun, 19 Nov 2023 16:19:08 +0100 Subject: [PATCH 2/6] Move RuleInterface to Contracts namespace --- src/{Rules/RuleInterface.php => Contracts/Rule.php} | 8 ++++---- src/Rules/AcceptedIfRule.php | 3 ++- src/Rules/AcceptedRule.php | 3 ++- src/Rules/ActiveURLRule.php | 3 ++- src/Rules/AlphaNumericRule.php | 3 ++- src/Rules/AlphaRule.php | 3 ++- src/Rules/BooleanRule.php | 3 ++- src/Rules/ConfirmedRule.php | 3 ++- src/Rules/EmailRule.php | 3 ++- src/Rules/FileRule.php | 3 ++- src/Rules/InRule.php | 3 ++- src/Rules/JsonRule.php | 3 ++- src/Rules/LowerCaseRule.php | 3 ++- src/Rules/MaxLengthRule.php | 3 ++- src/Rules/MinLengthRule.php | 3 ++- src/Rules/NotInRule.php | 3 ++- src/Rules/NullableRule.php | 3 ++- src/Rules/NumericRule.php | 3 ++- src/Rules/PasswordRule.php | 3 ++- src/Rules/RequiredRule.php | 3 ++- src/Rules/RequiredWithRule.php | 3 ++- src/Rules/SameRule.php | 3 ++- src/Rules/SizeRule.php | 3 ++- src/Rules/StringRule.php | 3 ++- src/Rules/UpperCaseRule.php | 3 ++- src/Rules/UrlRule.php | 3 ++- src/Rules/ValidIpRule.php | 3 ++- 27 files changed, 56 insertions(+), 30 deletions(-) rename src/{Rules/RuleInterface.php => Contracts/Rule.php} (81%) diff --git a/src/Rules/RuleInterface.php b/src/Contracts/Rule.php similarity index 81% rename from src/Rules/RuleInterface.php rename to src/Contracts/Rule.php index abd0f7d..3b99012 100644 --- a/src/Rules/RuleInterface.php +++ b/src/Contracts/Rule.php @@ -1,17 +1,17 @@ Date: Sun, 19 Nov 2023 16:40:36 +0100 Subject: [PATCH 3/6] Move RuleMaped to Mapping namespace --- .../RulesAlias.php} | 51 ++------------- src/Mapping/RulesMaped.php | 62 +++++++++++++++++++ src/Validator.php | 1 + 3 files changed, 67 insertions(+), 47 deletions(-) rename src/{RulesMaped.php => Mapping/RulesAlias.php} (65%) create mode 100644 src/Mapping/RulesMaped.php diff --git a/src/RulesMaped.php b/src/Mapping/RulesAlias.php similarity index 65% rename from src/RulesMaped.php rename to src/Mapping/RulesAlias.php index 7b6744e..23dd364 100644 --- a/src/RulesMaped.php +++ b/src/Mapping/RulesAlias.php @@ -1,18 +1,17 @@ UrlRule::class, 'ip' => ValidIpRule::class, ]; - - /** - * Get the mapping of rule aliases to their corresponding rule classes. - * - * @return array - */ - protected static function getRules(): array - { - return self::$rules; - } - - /** - * Get the rule class for a given alias. - * - * @param string $alias Rule alias to retrieve the corresponding rule class. - * @return string Rule class. - * @throws ValidatorException If the rule alias is not found. - */ - protected static function getRule(string $alias): string - { - if (isset(self::$rules[$alias]) && class_exists(self::$rules[$alias])) { - return self::$rules[$alias]; - } - - $translatedMessage = LangManager::getTranslation('validation.rule_not_found', [ - 'ruleName' => $alias, - ]); - - throw new ValidatorException($translatedMessage); - } - - /** - * Add a new rule to the mapping. - * - * @param string $alias Rule alias. - * @param string $className Rule class name. - * @return void - */ - public static function addRule(string $alias, string $className): void - { - self::$rules[$alias] = $className; - } } diff --git a/src/Mapping/RulesMaped.php b/src/Mapping/RulesMaped.php new file mode 100644 index 0000000..e72654d --- /dev/null +++ b/src/Mapping/RulesMaped.php @@ -0,0 +1,62 @@ + $alias, + ]); + + throw new ValidatorException($translatedMessage); + } + + /** + * Add a new rule to the mapping. + * + * @param string $alias Rule alias. + * @param string $className Rule class name. + * @return void + */ + public static function addRule(string $alias, string $className): void + { + self::$rules[$alias] = $className; + } +} diff --git a/src/Validator.php b/src/Validator.php index c4f5402..db5d3ec 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -11,6 +11,7 @@ namespace BlakvGhost\PHPValidator; +use BlakvGhost\PHPValidator\Mapping\RulesMaped; use BlakvGhost\PHPValidator\Rules\RuleInterface; use BlakvGhost\PHPValidator\ValidatorException; From 3b4a6e112336f3fdaec3a7291f86137ef93c932a Mon Sep 17 00:00:00 2001 From: Kabirou ALASSANE Date: Sun, 19 Nov 2023 16:52:11 +0100 Subject: [PATCH 4/6] Move LangManager to Lang namespace --- README.md | 2 +- src/{LangManager.php => Lang/Lang.php} | 44 +++------------------- src/Lang/LangManager.php | 51 ++++++++++++++++++++++++++ src/Mapping/RulesMaped.php | 4 +- src/Rules/AcceptedIfRule.php | 2 +- src/Rules/AcceptedRule.php | 2 +- src/Rules/ActiveURLRule.php | 2 +- src/Rules/AlphaNumericRule.php | 2 +- src/Rules/AlphaRule.php | 2 +- src/Rules/BooleanRule.php | 2 +- src/Rules/ConfirmedRule.php | 2 +- src/Rules/EmailRule.php | 2 +- src/Rules/FileRule.php | 2 +- src/Rules/InRule.php | 2 +- src/Rules/JsonRule.php | 2 +- src/Rules/LowerCaseRule.php | 2 +- src/Rules/MaxLengthRule.php | 2 +- src/Rules/MinLengthRule.php | 2 +- src/Rules/NotInRule.php | 2 +- src/Rules/NullableRule.php | 2 +- src/Rules/NumericRule.php | 2 +- src/Rules/PasswordRule.php | 2 +- src/Rules/RequiredRule.php | 2 +- src/Rules/RequiredWithRule.php | 2 +- src/Rules/SameRule.php | 2 +- src/Rules/SizeRule.php | 2 +- src/Rules/StringRule.php | 2 +- src/Rules/UpperCaseRule.php | 2 +- src/Rules/UrlRule.php | 2 +- src/Rules/ValidIpRule.php | 2 +- src/Validator.php | 1 + tests/Feature/RuleTest.php | 2 +- tests/Feature/ValidatorTest.php | 2 +- 33 files changed, 88 insertions(+), 70 deletions(-) rename src/{LangManager.php => Lang/Lang.php} (80%) create mode 100644 src/Lang/LangManager.php diff --git a/README.md b/README.md index 45ca19a..6206f79 100644 --- a/README.md +++ b/README.md @@ -258,7 +258,7 @@ In addition to the predefined rules, you can create custom validation rules by i namespace YourNameSpace\Rules; use BlakvGhost\PHPValidator\Rules\RuleInterface; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class CustomPasswordRule implements RuleInterface { diff --git a/src/LangManager.php b/src/Lang/Lang.php similarity index 80% rename from src/LangManager.php rename to src/Lang/Lang.php index 837de99..ea01b2b 100644 --- a/src/LangManager.php +++ b/src/Lang/Lang.php @@ -1,24 +1,24 @@ [ // French translations 'validation.empty_data' => 'Les données de validation ne peuvent pas être vides.', @@ -82,38 +82,4 @@ class LangManager 'validation.size' => "The :attribute field must have the required length :value.", ], ]; - - - /** - * Get the current language. - * - * @return string Current language code. - */ - private static function getLocal(): string - { - // Get the current language from environment variables, defaulting to 'en' (English) if not set. - return $_ENV['local'] ?? 'en'; - } - - /** - * Get a translated message for the given key. - * - * @param string $key Translation key. - * @param array|null $parameters Placeholder values to replace in the translated message. - * @return string Translated message. - */ - public static function getTranslation(string $key, ?array $parameters = []): string - { - // Get the translation for the current language and the provided key, or use the key itself if not found. - $translation = self::$translations[self::getLocal()][$key] ?? $key; - - // Replace placeholders in the translation with the provided values. - if ($parameters) { - foreach ($parameters as $placeholder => $value) { - $translation = str_replace(":$placeholder", $value, $translation); - } - } - - return $translation; - } } diff --git a/src/Lang/LangManager.php b/src/Lang/LangManager.php new file mode 100644 index 0000000..ef9ef3d --- /dev/null +++ b/src/Lang/LangManager.php @@ -0,0 +1,51 @@ + $value) { + $translation = str_replace(":$placeholder", $value, $translation); + } + } + + return $translation; + } +} diff --git a/src/Mapping/RulesMaped.php b/src/Mapping/RulesMaped.php index e72654d..15be48c 100644 --- a/src/Mapping/RulesMaped.php +++ b/src/Mapping/RulesMaped.php @@ -11,13 +11,13 @@ namespace BlakvGhost\PHPValidator\Mapping; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; use BlakvGhost\PHPValidator\ValidatorException; class RulesMaped { use RulesAlias; - + /** * Get the mapping of rule aliases to their corresponding rule classes. * diff --git a/src/Rules/AcceptedIfRule.php b/src/Rules/AcceptedIfRule.php index 8ec28a4..37f5356 100644 --- a/src/Rules/AcceptedIfRule.php +++ b/src/Rules/AcceptedIfRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class AcceptedIfRule implements Rule { diff --git a/src/Rules/AcceptedRule.php b/src/Rules/AcceptedRule.php index 5fd2cf6..dc861f5 100644 --- a/src/Rules/AcceptedRule.php +++ b/src/Rules/AcceptedRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class AcceptedRule implements Rule { diff --git a/src/Rules/ActiveURLRule.php b/src/Rules/ActiveURLRule.php index 7a00f9b..f722e1e 100644 --- a/src/Rules/ActiveURLRule.php +++ b/src/Rules/ActiveURLRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class ActiveURLRule implements Rule { diff --git a/src/Rules/AlphaNumericRule.php b/src/Rules/AlphaNumericRule.php index ccffdc4..d2a0f8d 100644 --- a/src/Rules/AlphaNumericRule.php +++ b/src/Rules/AlphaNumericRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class AlphaNumericRule implements Rule { diff --git a/src/Rules/AlphaRule.php b/src/Rules/AlphaRule.php index 98390e1..10e3aeb 100644 --- a/src/Rules/AlphaRule.php +++ b/src/Rules/AlphaRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class AlphaRule implements Rule { diff --git a/src/Rules/BooleanRule.php b/src/Rules/BooleanRule.php index faa46e1..df683e6 100644 --- a/src/Rules/BooleanRule.php +++ b/src/Rules/BooleanRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class BooleanRule implements Rule { diff --git a/src/Rules/ConfirmedRule.php b/src/Rules/ConfirmedRule.php index d3299ad..372622f 100644 --- a/src/Rules/ConfirmedRule.php +++ b/src/Rules/ConfirmedRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class ConfirmedRule implements Rule { diff --git a/src/Rules/EmailRule.php b/src/Rules/EmailRule.php index 21f467c..89da2a0 100644 --- a/src/Rules/EmailRule.php +++ b/src/Rules/EmailRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class EmailRule implements Rule { diff --git a/src/Rules/FileRule.php b/src/Rules/FileRule.php index 55c25f9..2e1520d 100644 --- a/src/Rules/FileRule.php +++ b/src/Rules/FileRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class FileRule implements Rule { diff --git a/src/Rules/InRule.php b/src/Rules/InRule.php index 01313bb..0e654a1 100644 --- a/src/Rules/InRule.php +++ b/src/Rules/InRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class InRule implements Rule { diff --git a/src/Rules/JsonRule.php b/src/Rules/JsonRule.php index e80f520..21a98cf 100644 --- a/src/Rules/JsonRule.php +++ b/src/Rules/JsonRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class JsonRule implements Rule { diff --git a/src/Rules/LowerCaseRule.php b/src/Rules/LowerCaseRule.php index 6e3d1a5..5bce432 100644 --- a/src/Rules/LowerCaseRule.php +++ b/src/Rules/LowerCaseRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class LowerCaseRule implements Rule { diff --git a/src/Rules/MaxLengthRule.php b/src/Rules/MaxLengthRule.php index c50890d..a19723b 100644 --- a/src/Rules/MaxLengthRule.php +++ b/src/Rules/MaxLengthRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class MaxLengthRule implements Rule { diff --git a/src/Rules/MinLengthRule.php b/src/Rules/MinLengthRule.php index 7e3942c..cf38a0c 100644 --- a/src/Rules/MinLengthRule.php +++ b/src/Rules/MinLengthRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class MinLengthRule implements Rule { diff --git a/src/Rules/NotInRule.php b/src/Rules/NotInRule.php index 9154477..e1a018c 100644 --- a/src/Rules/NotInRule.php +++ b/src/Rules/NotInRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class NotInRule implements Rule { diff --git a/src/Rules/NullableRule.php b/src/Rules/NullableRule.php index 4396b98..35b962a 100644 --- a/src/Rules/NullableRule.php +++ b/src/Rules/NullableRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class NullableRule implements Rule { diff --git a/src/Rules/NumericRule.php b/src/Rules/NumericRule.php index c35751c..654e5d4 100644 --- a/src/Rules/NumericRule.php +++ b/src/Rules/NumericRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class NumericRule implements Rule { diff --git a/src/Rules/PasswordRule.php b/src/Rules/PasswordRule.php index 66a112f..1df6844 100644 --- a/src/Rules/PasswordRule.php +++ b/src/Rules/PasswordRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class PasswordRule implements Rule { diff --git a/src/Rules/RequiredRule.php b/src/Rules/RequiredRule.php index 7f5da6a..08be9e2 100644 --- a/src/Rules/RequiredRule.php +++ b/src/Rules/RequiredRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class RequiredRule implements Rule { diff --git a/src/Rules/RequiredWithRule.php b/src/Rules/RequiredWithRule.php index d853539..6b67435 100644 --- a/src/Rules/RequiredWithRule.php +++ b/src/Rules/RequiredWithRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class RequiredWithRule implements Rule { diff --git a/src/Rules/SameRule.php b/src/Rules/SameRule.php index 200a689..73246d3 100644 --- a/src/Rules/SameRule.php +++ b/src/Rules/SameRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class SameRule implements Rule { diff --git a/src/Rules/SizeRule.php b/src/Rules/SizeRule.php index 5b20be2..eea3aaf 100644 --- a/src/Rules/SizeRule.php +++ b/src/Rules/SizeRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class SizeRule implements Rule { diff --git a/src/Rules/StringRule.php b/src/Rules/StringRule.php index 1fe4a76..6754906 100644 --- a/src/Rules/StringRule.php +++ b/src/Rules/StringRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class StringRule implements Rule { diff --git a/src/Rules/UpperCaseRule.php b/src/Rules/UpperCaseRule.php index 8165980..5d7452f 100644 --- a/src/Rules/UpperCaseRule.php +++ b/src/Rules/UpperCaseRule.php @@ -12,7 +12,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class UpperCaseRule implements Rule { diff --git a/src/Rules/UrlRule.php b/src/Rules/UrlRule.php index 86963ee..dc50e12 100644 --- a/src/Rules/UrlRule.php +++ b/src/Rules/UrlRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class UrlRule implements Rule { diff --git a/src/Rules/ValidIpRule.php b/src/Rules/ValidIpRule.php index c66a72f..7509af6 100644 --- a/src/Rules/ValidIpRule.php +++ b/src/Rules/ValidIpRule.php @@ -11,7 +11,7 @@ namespace BlakvGhost\PHPValidator\Rules; use BlakvGhost\PHPValidator\Contracts\Rule; -use BlakvGhost\PHPValidator\LangManager; +use BlakvGhost\PHPValidator\Lang\LangManager; class ValidIpRule implements Rule { diff --git a/src/Validator.php b/src/Validator.php index db5d3ec..30b5438 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -11,6 +11,7 @@ namespace BlakvGhost\PHPValidator; +use BlakvGhost\PHPValidator\Lang\LangManager; use BlakvGhost\PHPValidator\Mapping\RulesMaped; use BlakvGhost\PHPValidator\Rules\RuleInterface; use BlakvGhost\PHPValidator\ValidatorException; diff --git a/tests/Feature/RuleTest.php b/tests/Feature/RuleTest.php index ae56eba..1591337 100644 --- a/tests/Feature/RuleTest.php +++ b/tests/Feature/RuleTest.php @@ -1,6 +1,6 @@ new Validator([], ['name' => 'string'])) From c57f68d66372e5852304afbef663614b82b83b1f Mon Sep 17 00:00:00 2001 From: Kabirou ALASSANE Date: Sun, 19 Nov 2023 17:25:30 +0100 Subject: [PATCH 5/6] Fix custom validatation error message issues and formating with prettier --- README.md | 20 ++++++++++++++++++++ src/Lang/LangManager.php | 2 +- src/Rules/AcceptedIfRule.php | 4 ++-- src/Rules/EmailRule.php | 4 ++-- src/Rules/JsonRule.php | 10 +++++----- src/Rules/SizeRule.php | 6 +++--- src/Rules/UrlRule.php | 2 +- src/Rules/ValidIpRule.php | 2 +- src/Validator.php | 19 +++++++++++-------- tests/Feature/RuleTest.php | 16 ++++++++-------- tests/Feature/ValidatorTest.php | 14 +++++++++----- 11 files changed, 63 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 6206f79..99fb2d2 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,26 @@ try { } ``` +You can also customize the validation error messages according to the field + +```php +$data = [ + 'username' => 'BlakvGhost', +]; + +$validator = new Validator( + $data, + [ + 'username' => 'required|string', + ], + [ + 'username' => [ + 'required' => 'Votre nom d\'utilisateur doit être présent', + 'string' => 'Votre nom d\'utilisateur doit forcément être une chaîne de caractère', + ], + ] + ); +``` ## Features diff --git a/src/Lang/LangManager.php b/src/Lang/LangManager.php index ef9ef3d..b014855 100644 --- a/src/Lang/LangManager.php +++ b/src/Lang/LangManager.php @@ -13,7 +13,7 @@ class LangManager { - + use Lang; /** diff --git a/src/Rules/AcceptedIfRule.php b/src/Rules/AcceptedIfRule.php index 37f5356..22aea29 100644 --- a/src/Rules/AcceptedIfRule.php +++ b/src/Rules/AcceptedIfRule.php @@ -61,8 +61,8 @@ public function passes(string $field, $value, array $data): bool /** * Get the validation error message for the accepted if rule. * - * @return string Validation error message. - */ + * @return string Validation error message. + */ public function message(): string { // Use LangManager to get a translated validation error message. diff --git a/src/Rules/EmailRule.php b/src/Rules/EmailRule.php index 89da2a0..176ba1f 100644 --- a/src/Rules/EmailRule.php +++ b/src/Rules/EmailRule.php @@ -55,10 +55,10 @@ public function passes(string $field, $value, array $data): bool */ public function message(): string { - + // Use LangManager to get a translated validation error message. return LangManager::getTranslation('validation.email_rule', [ 'attribute' => $this->field, ]); } -} \ No newline at end of file +} diff --git a/src/Rules/JsonRule.php b/src/Rules/JsonRule.php index 21a98cf..d63c059 100644 --- a/src/Rules/JsonRule.php +++ b/src/Rules/JsonRule.php @@ -45,11 +45,11 @@ public function passes(string $field, $value, array $data): bool // Set the field property for use in the message method. $this->field = $field; - if (!empty($value)) { - return is_string($value) && - is_array(json_decode($value, true)) ? true : false; - } - return false; + if (!empty($value)) { + return is_string($value) && + is_array(json_decode($value, true)) ? true : false; + } + return false; } /** diff --git a/src/Rules/SizeRule.php b/src/Rules/SizeRule.php index eea3aaf..454eaee 100644 --- a/src/Rules/SizeRule.php +++ b/src/Rules/SizeRule.php @@ -56,7 +56,7 @@ public function passes(string $field, $value, array $data): bool return $value == $total; } - + if (is_array($value)) { return count($value) == $total; @@ -67,10 +67,10 @@ public function passes(string $field, $value, array $data): bool if (isset($_FILES[$value]) && $_FILES[$value]["error"] == 0) { // Get the file size in bytes $size = $_FILES[$value]["size"]; - + // Convert bytes to kilobytes $size_kb = $size / 1024; // kilobytes - + return $size_kb == $total; } diff --git a/src/Rules/UrlRule.php b/src/Rules/UrlRule.php index dc50e12..768fa00 100644 --- a/src/Rules/UrlRule.php +++ b/src/Rules/UrlRule.php @@ -45,7 +45,7 @@ public function passes(string $field, $value, array $data): bool // Set the field property for use in the message method. $this->field = $field; - return filter_var($value, FILTER_VALIDATE_URL); + return filter_var($value, FILTER_VALIDATE_URL); } /** diff --git a/src/Rules/ValidIpRule.php b/src/Rules/ValidIpRule.php index 7509af6..5097c67 100644 --- a/src/Rules/ValidIpRule.php +++ b/src/Rules/ValidIpRule.php @@ -45,7 +45,7 @@ public function passes(string $field, $value, array $data): bool // Set the field property for use in the message method. $this->field = $field; - return filter_var($value, FILTER_VALIDATE_IP); + return filter_var($value, FILTER_VALIDATE_IP); } /** diff --git a/src/Validator.php b/src/Validator.php index 30b5438..c315c46 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -28,11 +28,11 @@ class Validator extends RulesMaped * @param array $rules Validation rules to apply. * @param array $messages Validation rules messages to apply when failed. */ - public function __construct(private array $data, - private array $rules, - private array $messages = [] - ) - { + public function __construct( + private array $data, + private array $rules, + private array $messages = [] + ) { $this->validateConstructorInputs(); $this->validate(); } @@ -103,7 +103,7 @@ protected function validate() $validator = new $ruleClass($parameters); - $this->checkPasses($validator, $field); + $this->checkPasses($validator, $field, $ruleName); } } } @@ -114,12 +114,15 @@ protected function validate() * * @param mixed $validator Instance of the rule to check. * @param string $field Field associated with the rule. + * @param ?string $ruleName Associated rule alias. */ - protected function checkPasses(mixed $validator, string $field) + protected function checkPasses(mixed $validator, string $field, ?string $ruleName = null) { if (isset($this->data[$field]) && !$validator->passes($field, $this->data[$field], $this->data)) { - $message = isset($this->messages[$field]) ? $this->messages[$field] : $validator->message(); + $assert = isset($ruleName) && isset($this->messages[$field][$ruleName]); + + $message = $assert ? $this->messages[$field][$ruleName] : $validator->message(); $this->addError($field, $message); } diff --git a/tests/Feature/RuleTest.php b/tests/Feature/RuleTest.php index 1591337..c80709b 100644 --- a/tests/Feature/RuleTest.php +++ b/tests/Feature/RuleTest.php @@ -127,7 +127,7 @@ $validator = new Validator(['field' => 'value', 'other_field' => 'different_value'], ['field' => 'same:other_field']); expect($validator->isValid())->toBeFalse(); - + $validator = new Validator(['field' => 'value'], ['field' => 'same:other_field']); expect($validator->isValid())->toBeFalse(); @@ -143,7 +143,7 @@ $validator = new Validator(['password' => 'StrongPwd1'], ['password' => 'password:8']); expect($validator->isValid())->toBeTrue(); - + $validator = new Validator(['password' => 'StrongPwd1'], ['password' => 'password']); expect($validator->isValid())->toBeTrue(); @@ -152,10 +152,10 @@ $validator = new Validator(['password' => 'lowercase1'], ['password' => 'password']); expect($validator->isValid())->toBeFalse(); - + $validator = new Validator(['password' => 'UPPERCASE1'], ['password' => 'password']); expect($validator->isValid())->toBeFalse(); - + $validator = new Validator(['password' => 'NoDigit'], ['password' => 'password']); expect($validator->isValid())->toBeFalse(); @@ -363,7 +363,7 @@ $validator = new Validator(['field' => false], ['field' => 'bool']); expect($validator->isValid())->toBeTrue(); - + $validator = new Validator(['field' => 'string'], ['field' => 'bool']); expect($validator->isValid())->toBeFalse(); @@ -378,10 +378,10 @@ $validator = new Validator(['field' => ""], ['field' => 'json']); expect($validator->isValid())->toBeFalse(); - + $validator = new Validator(['field' => '{"name":"vishal", "email": "abc@gmail.com"}'], ['field' => 'json']); expect($validator->isValid())->toBeTrue(); - + $validator = new Validator(['field' => '{name:vishal, email: abc@gmail.com}'], ['field' => 'json']); expect($validator->isValid())->toBeFalse(); @@ -393,7 +393,7 @@ }); it('validates url rule successfully', function () { - + $validator = new Validator(['field' => 'http://google.com'], ['field' => 'url']); expect($validator->isValid())->toBeTrue(); diff --git a/tests/Feature/ValidatorTest.php b/tests/Feature/ValidatorTest.php index 5b3a36c..1ae3d98 100644 --- a/tests/Feature/ValidatorTest.php +++ b/tests/Feature/ValidatorTest.php @@ -24,11 +24,15 @@ $errorMessage = "Je teste une règle custom"; $validator = new Validator( - ['field' => ''], - ['field' => 'required'], - ['field' => $errorMessage] - ); + ['field' => ''], + ['field' => 'required'], + [ + 'field' => [ + 'required' => $errorMessage + ] + ] + ); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe($errorMessage); -}); \ No newline at end of file +}); From 7424517752f792ace1b8122f17ef02c7a0e0b843 Mon Sep 17 00:00:00 2001 From: Kabirou ALASSANE Date: Sun, 19 Nov 2023 17:51:59 +0100 Subject: [PATCH 6/6] Update documentation with new way to validate with custom error message --- README.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 99fb2d2..0e91538 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ try { } ``` -You can also customize the validation error messages according to the field +You can also customize the validation error messages ```php $data = [ @@ -73,7 +73,7 @@ $validator = new Validator( - `Predefined Rules`: PHPValidator comes with a set of predefined validation rules such as required, string, email, maxLength etc. -- `Custom Rules`: Easily create custom validation rules by implementing the `RuleInterface`. +- `Custom Rules`: Easily create custom validation rules by implementing the `Rule` Interface. - `Multilingual Support`: Customize validation error messages based on the application's language using the `LangManager`. @@ -269,7 +269,7 @@ PHPValidator provides a variety of predefined rules that you can use for data va ``` ## Custom Rule -In addition to the predefined rules, you can create custom validation rules by implementing the `RuleInterface`. Here's an example of how to create and use a custom rule: +In addition to the predefined rules, you can create custom validation rules by implementing the `Rule` Interface. Here's an example of how to create and use a custom rule: ### CustomPasswordRule.php @@ -277,10 +277,9 @@ In addition to the predefined rules, you can create custom validation rules by i // CustomPasswordRule.php namespace YourNameSpace\Rules; -use BlakvGhost\PHPValidator\Rules\RuleInterface; -use BlakvGhost\PHPValidator\Lang\LangManager; +use BlakvGhost\PHPValidator\Contracts\Rule; -class CustomPasswordRule implements RuleInterface +class CustomPasswordRule implements Rule { protected $field; @@ -310,6 +309,7 @@ class CustomPasswordRule implements RuleInterface use BlakvGhost\PHPValidator\Validator; use BlakvGhost\PHPValidator\ValidatorException; + use YourNameSpace\CustomPasswordRule; @@ -344,7 +344,8 @@ class CustomPasswordRule implements RuleInterface use BlakvGhost\PHPValidator\Validator; use BlakvGhost\PHPValidator\ValidatorException; - use BlakvGhost\PHPValidator\RulesMaped; + use BlakvGhost\PHPValidator\Mapping\RulesMaped; + use YourNameSpace\CustomPasswordRule; // Add your rule here using an alias and the full namespace of your custom class