diff --git a/README.md b/README.md index 218f8e9..8c84775 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ try { $validator = new Validator($data, [ 'username' => 'required|string', 'email' => 'required|email', - 'score' => ['required','max_length:200', new CustomRule()], + 'score' => ['required','max:200', new CustomRule()], 'password' => new CustomRule(), ]); @@ -87,7 +87,7 @@ PHPValidator provides a variety of predefined rules that you can use for data va - Specifies the maximum length of a string field. ```php - 'username' => 'max_length:25' + 'username' => 'max:25' ``` 5. **Confirmed Rule** @@ -143,14 +143,14 @@ PHPValidator provides a variety of predefined rules that you can use for data va - Validates that a field contains only lowercase alphabetic characters. ```php - 'username' => 'lower' + 'username' => 'lowercase' ``` 13. **Uppercase Rule** - Validates that a field contains only uppercase alphabetic characters. ```php - 'username' => 'upper' + 'username' => 'uppercase' ``` 14. **In Rule** @@ -184,7 +184,7 @@ PHPValidator provides a variety of predefined rules that you can use for data va - Specifies the minimum length of a string field. ```php - 'username' => 'min_length:8' + 'username' => 'min:8' ``` 19. **Not In Rule** - Validates that a field's value is not in a specified set. @@ -204,7 +204,7 @@ PHPValidator provides a variety of predefined rules that you can use for data va - Validates that a field's value is a valid IP address. ```php - 'client_ip' => 'valid_ip', + 'client_ip' => 'ip', ``` 22. **Json Rule** @@ -221,17 +221,19 @@ PHPValidator provides a variety of predefined rules that you can use for data va 'website' => 'url', ``` 24. **Alpha Numeric Rule** + - Validates that a field's value contains only alphanumeric characters. ```php - 'pseudo' => 'alpha_numeric', + 'pseudo' => 'alpha_num', ``` 25. **Boolean Rule** + - Validates that a field's value is a boolean. ```php - 'is_admin' => 'boolean', + 'is_admin' => 'bool', ``` 26. **Size Rule** @@ -282,38 +284,74 @@ class CustomPasswordRule implements RuleInterface ``` ### Usage in Validator -```php +- Use your custom class directly -use BlakvGhost\PHPValidator\Validator; -use BlakvGhost\PHPValidator\ValidatorException; -use YourNameSpace\CustomPasswordRule; + ```php + use BlakvGhost\PHPValidator\Validator; + use BlakvGhost\PHPValidator\ValidatorException; + use YourNameSpace\CustomPasswordRule; -// ... -try { + // ... - $data = [ - 'password' => '42', - 'confirm_password' => '142', - ]; - // or - // $data = $_POST; + try { - $validator = new Validator($data, [ - 'password' => ['required', new CustomPasswordRule()], - ]); + $data = [ + 'password' => '42', + 'confirm_password' => '142', + ]; + // or + // $data = $_POST; - if ($validator->isValid()) { - echo "Validation passed!"; - } else { - $errors = $validator->getErrors(); - print_r($errors); + $validator = new Validator($data, [ + 'password' => ['required', new CustomPasswordRule()], + ]); + + if ($validator->isValid()) { + echo "Validation passed!"; + } else { + $errors = $validator->getErrors(); + print_r($errors); + } + } catch (ValidatorException $e) { + echo "Validation error: " . $e->getMessage(); } -} catch (ValidatorException $e) { - echo "Validation error: " . $e->getMessage(); -} -``` + ``` +- Add your custom class to the rules list and use it as if it were native + + ```php + + use BlakvGhost\PHPValidator\Validator; + use BlakvGhost\PHPValidator\ValidatorException; + use BlakvGhost\PHPValidator\RulesMaped; + use YourNameSpace\CustomPasswordRule; + + // Add your rule here using an alias and the full namespace of your custom class + RulesMaped::addRule('c_password', CustomPasswordRule::class); + + try { + + $data = [ + 'password' => '42', + 'confirm_password' => '142', + ]; + + $validator = new Validator($data, [ + 'password' => 'required|c_password', + ]); + + if ($validator->isValid()) { + echo "Validation passed!"; + } else { + $errors = $validator->getErrors(); + print_r($errors); + } + } catch (ValidatorException $e) { + echo "Validation error: " . $e->getMessage(); + } + ``` + In this example, we created a CustomPasswordRule that checks if the password is equal to confirm_password. You can customize the passes method to implement your specific validation logic. ## Contributing diff --git a/src/Rules/ActiveURLRule.php b/src/Rules/ActiveURLRule.php index d9268eb..5b05489 100644 --- a/src/Rules/ActiveURLRule.php +++ b/src/Rules/ActiveURLRule.php @@ -13,7 +13,7 @@ use BlakvGhost\PHPValidator\LangManager; -class ActiveUrlRule implements RuleInterface +class ActiveURLRule implements RuleInterface { /** * The name of the field being validated. @@ -23,7 +23,7 @@ class ActiveUrlRule implements RuleInterface protected $field; /** - * Constructor of the ActiveUrlRule class. + * Constructor of the ActiveURLRule class. * * @param array $parameters Parameters for the rule (none needed for this rule). */ diff --git a/src/Rules/LowerRule.php b/src/Rules/LowerCaseRule.php similarity index 91% rename from src/Rules/LowerRule.php rename to src/Rules/LowerCaseRule.php index af9034d..223a58e 100644 --- a/src/Rules/LowerRule.php +++ b/src/Rules/LowerCaseRule.php @@ -1,7 +1,7 @@ AcceptedRule::class, + 'accepted_if' => AcceptedIfRule::class, + 'active_url' => ActiveURLRule::class, + 'alpha' => AlphaRule::class, + 'alpha_num' => AlphaNumericRule::class, + 'bool' => BooleanRule::class, + 'confirmed' => ConfirmedRule::class, + 'email' => EmailRule::class, + 'file' => FileRule::class, + 'in' => InRule::class, + 'not_in' => NotInRule::class, + 'string' => StringRule::class, + 'required' => RequiredRule::class, + 'required_with' => RequiredWithRule::class, + 'lowercase' => LowerCaseRule::class, + 'uppercase' => UpperCaseRule::class, + 'json' => JsonRule::class, + 'max' => MaxLengthRule::class, + 'min' => MinLengthRule::class, + 'nullable' => NullableRule::class, + 'numeric' => NumericRule::class, + 'password' => PasswordRule::class, + 'same' => SameRule::class, + 'size' => SizeRule::class, + 'url' => 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/Validator.php b/src/Validator.php index 9fe41f7..3aa8a46 100644 --- a/src/Validator.php +++ b/src/Validator.php @@ -14,7 +14,7 @@ use BlakvGhost\PHPValidator\Rules\RuleInterface; use BlakvGhost\PHPValidator\ValidatorException; -class Validator +class Validator extends RulesMaped { private $errors = []; @@ -60,21 +60,7 @@ protected function resolveRuleClass($ruleName): string return $ruleName::class; } - $ruleParts = explode('_', $ruleName); - $className = implode('', array_map('ucfirst', $ruleParts)) . 'Rule'; - - $fullClassName = "BlakvGhost\\PHPValidator\\Rules\\$className"; - - if (!class_exists($fullClassName)) { - - $translatedMessage = LangManager::getTranslation('validation.rule_not_found', [ - 'ruleName' => $ruleName, - ]); - - throw new ValidatorException($translatedMessage); - } - - return $fullClassName; + return $this->getRule($ruleName); } /** diff --git a/tests/Feature/RuleTest.php b/tests/Feature/RuleTest.php index 5703eeb..ae56eba 100644 --- a/tests/Feature/RuleTest.php +++ b/tests/Feature/RuleTest.php @@ -19,10 +19,10 @@ it('validates max length rule successfully', function () { - $validator = new Validator(['username' => 'value'], ['username' => 'max_length:5']); + $validator = new Validator(['username' => 'value'], ['username' => 'max:5']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['username' => 'value_long'], ['username' => 'max_length:5']); + $validator = new Validator(['username' => 'value_long'], ['username' => 'max:5']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['username'][0])->toBe( @@ -61,10 +61,10 @@ it('validates min length rule successfully', function () { - $validator = new Validator(['field' => 'toolongvalue'], ['field' => 'min_length:10']); + $validator = new Validator(['field' => 'toolongvalue'], ['field' => 'min:10']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['field' => 'less'], ['field' => 'min_length:10']); + $validator = new Validator(['field' => 'less'], ['field' => 'min:10']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe( @@ -285,10 +285,10 @@ it('validates lowercase rule successfully', function () { - $validator = new Validator(['field' => 'lowercase'], ['field' => 'lower']); + $validator = new Validator(['field' => 'lowercase'], ['field' => 'lowercase']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['field' => 'UPPERCASE'], ['field' => 'lower']); + $validator = new Validator(['field' => 'UPPERCASE'], ['field' => 'lowercase']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe( @@ -300,10 +300,10 @@ it('validates uppercase rule successfully', function () { - $validator = new Validator(['field' => 'UPPERCASE'], ['field' => 'upper']); + $validator = new Validator(['field' => 'UPPERCASE'], ['field' => 'uppercase']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['field' => 'lowercase'], ['field' => 'upper']); + $validator = new Validator(['field' => 'lowercase'], ['field' => 'uppercase']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe( @@ -328,12 +328,12 @@ ); }); -it('validates alpha_numeric rule successfully', function () { +it('validates alpha numeric rule successfully', function () { - $validator = new Validator(['field' => 'alpha2324'], ['field' => 'alpha_numeric']); + $validator = new Validator(['field' => 'alpha2324'], ['field' => 'alpha_num']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['field' => 's$sdfde$*'], ['field' => 'alpha_numeric']); + $validator = new Validator(['field' => 's$sdfde$*'], ['field' => 'alpha_num']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe( @@ -361,10 +361,10 @@ it('validates boolean rule successfully', function () { - $validator = new Validator(['field' => false], ['field' => 'boolean']); + $validator = new Validator(['field' => false], ['field' => 'bool']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['field' => 'string'], ['field' => 'boolean']); + $validator = new Validator(['field' => 'string'], ['field' => 'bool']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe( @@ -409,10 +409,10 @@ it('validates ip rule successfully', function () { - $validator = new Validator(['field' => '127.0.0.1'], ['field' => 'valid_ip']); + $validator = new Validator(['field' => '127.0.0.1'], ['field' => 'ip']); expect($validator->isValid())->toBeTrue(); - $validator = new Validator(['field' => '3853598'], ['field' => 'valid_ip']); + $validator = new Validator(['field' => '3853598'], ['field' => 'ip']); expect($validator->isValid())->toBeFalse(); expect($validator->getErrors()['field'][0])->toBe(