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