| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Support\Validation\Rules; |
| 6 |
|
| 7 |
use Metricool\Support\Validation\Exceptions\RuleFailedException; |
| 8 |
|
| 9 |
abstract class AbstractRule |
| 10 |
{ |
| 11 |
/** |
| 12 |
* The parameters of the rule, e.g. "min:8" has the parameter "8". |
| 13 |
* @var string[] |
| 14 |
*/ |
| 15 |
protected array $parameters; |
| 16 |
|
| 17 |
public function __construct(array $parameters = []) |
| 18 |
{ |
| 19 |
$this->parameters = $parameters; |
| 20 |
} |
| 21 |
|
| 22 |
/** |
| 23 |
* Validates the given value according to the rule. |
| 24 |
* @param string $field The name of the field under validation |
| 25 |
* @param mixed $value The value under validation |
| 26 |
* @param array $data All the data under validation, for rules that depend |
| 27 |
* on other fields |
| 28 |
* @throws RuleFailedException when the rule fails |
| 29 |
*/ |
| 30 |
abstract public function validate(string $field, $value, array $data): void; |
| 31 |
|
| 32 |
/** |
| 33 |
* Whether the rule is required. Required rules are run by the Validator |
| 34 |
* before all other rules and stop the validation of the field when they |
| 35 |
* fail, e.g. the required rule. Override this method to make a rule |
| 36 |
* required. |
| 37 |
*/ |
| 38 |
public function isRequired(): bool |
| 39 |
{ |
| 40 |
return false; |
| 41 |
} |
| 42 |
|
| 43 |
/** |
| 44 |
* Fail the rule with the given error message. |
| 45 |
* @throws RuleFailedException |
| 46 |
*/ |
| 47 |
protected function fail(string $message): void |
| 48 |
{ |
| 49 |
// phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Messages are collected by the Validator and returned as JSON |
| 50 |
throw new RuleFailedException($message); |
| 51 |
} |
| 52 |
|
| 53 |
/** |
| 54 |
* Get the size of a value for size based rules. Uses the numeric value |
| 55 |
* for numbers, the length for strings and the count for arrays. |
| 56 |
* @param mixed $value |
| 57 |
*/ |
| 58 |
protected function sizeOf($value): float |
| 59 |
{ |
| 60 |
if (is_numeric($value)) { |
| 61 |
return (float) $value; |
| 62 |
} |
| 63 |
|
| 64 |
if (is_array($value)) { |
| 65 |
return (float) count($value); |
| 66 |
} |
| 67 |
|
| 68 |
return (float) mb_strlen((string) $value); |
| 69 |
} |
| 70 |
} |
| 71 |
|