Commands
1 year ago
Concerns
1 year ago
Contracts
1 year ago
Exceptions
1 year ago
Rules
1 year ago
Config.php
1 year ago
ServiceProvider.php
1 year ago
ValidationRuleSet.php
1 year ago
ValidationRulesRegistrar.php
1 year ago
Validator.php
1 year ago
ValidationRulesRegistrar.php
75 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Give\Vendors\StellarWP\Validation; |
| 6 | |
| 7 | use Give\Vendors\StellarWP\Validation\Contracts\ValidationRule; |
| 8 | |
| 9 | /** |
| 10 | * @since 1.0.0 |
| 11 | */ |
| 12 | class ValidationRulesRegistrar |
| 13 | { |
| 14 | /** |
| 15 | * @var array<string, class-string<ValidationRule>> |
| 16 | */ |
| 17 | protected array $rules = []; |
| 18 | |
| 19 | /** |
| 20 | * Register one or many validation rules. |
| 21 | * |
| 22 | * @since 1.0.0 |
| 23 | */ |
| 24 | public function register(string ...$rules): self |
| 25 | { |
| 26 | foreach ($rules as $rule) { |
| 27 | $this->registerClass($rule); |
| 28 | } |
| 29 | |
| 30 | return $this; |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Register a validation rule. |
| 35 | * |
| 36 | * @since 1.2.1 switch to throwing InvalidArgumentException from Config |
| 37 | * @since 1.0.0 |
| 38 | */ |
| 39 | private function registerClass(string $class): self |
| 40 | { |
| 41 | if (!is_subclass_of($class, ValidationRule::class)) { |
| 42 | Config::throwInvalidArgumentException( |
| 43 | sprintf( |
| 44 | 'Validation rule must implement %s', |
| 45 | ValidationRule::class |
| 46 | ) |
| 47 | ); |
| 48 | } |
| 49 | |
| 50 | $classId = $class::id(); |
| 51 | |
| 52 | if (isset($this->rules[$classId])) { |
| 53 | Config::throwInvalidArgumentException( |
| 54 | "A validation rule with the id $classId has already been registered." |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | $this->rules[$classId] = $class; |
| 59 | |
| 60 | return $this; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Get a validation rule. |
| 65 | * |
| 66 | * @return string|null |
| 67 | * @since 2.12.0 |
| 68 | * |
| 69 | */ |
| 70 | public function getRule(string $ruleId) |
| 71 | { |
| 72 | return $this->rules[$ruleId] ?? null; |
| 73 | } |
| 74 | } |
| 75 |