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