Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 1 | <?php |
| 2 | |
| 3 | namespace LdapRecord\Configuration\Validators; |
| 4 | |
| 5 | use LdapRecord\Configuration\ConfigurationException; |
| 6 | |
| 7 | abstract class Validator |
| 8 | { |
| 9 | /** |
| 10 | * The configuration key under validation. |
| 11 | * |
| 12 | * @var string |
| 13 | */ |
| 14 | protected $key; |
| 15 | |
| 16 | /** |
| 17 | * The configuration value under validation. |
| 18 | * |
| 19 | * @var mixed |
| 20 | */ |
| 21 | protected $value; |
| 22 | |
| 23 | /** |
| 24 | * The validation exception message. |
| 25 | * |
| 26 | * @var string |
| 27 | */ |
| 28 | protected $message; |
| 29 | |
| 30 | /** |
| 31 | * Constructor. |
| 32 | * |
| 33 | * @param string $key |
| 34 | * @param mixed $value |
| 35 | */ |
| 36 | public function __construct($key, $value) |
| 37 | { |
| 38 | $this->key = $key; |
| 39 | $this->value = $value; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * Determine if the validation rule passes. |
| 44 | * |
| 45 | * @return bool |
| 46 | */ |
| 47 | abstract public function passes(); |
| 48 | |
| 49 | /** |
| 50 | * Validate the configuration value. |
| 51 | * |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 52 | * @return bool |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 53 | * |
| 54 | * @throws ConfigurationException |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 55 | */ |
| 56 | public function validate() |
| 57 | { |
| 58 | if (! $this->passes()) { |
| 59 | $this->fail(); |
| 60 | } |
| 61 | |
| 62 | return true; |
| 63 | } |
| 64 | |
| 65 | /** |
| 66 | * Throw a configuration exception. |
| 67 | * |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 68 | * @return void |
Matthias Andreas Benkard | 1ba5381 | 2022-12-27 17:32:58 +0100 | [diff] [blame^] | 69 | * |
| 70 | * @throws ConfigurationException |
Matthias Andreas Benkard | 7b2a3a1 | 2021-08-16 10:57:25 +0200 | [diff] [blame] | 71 | */ |
| 72 | protected function fail() |
| 73 | { |
| 74 | throw new ConfigurationException( |
| 75 | str_replace(':option', $this->key, $this->message) |
| 76 | ); |
| 77 | } |
| 78 | } |