Lines
93.33%
14 / 15
Methods
75.00%
3 / 4
Classes
0.00%
0 / 1
| Name | Lines | Methods | CRAP | ||||
|---|---|---|---|---|---|---|---|
| defaultMessage | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | ||
| validate | 83.33% | 5 / 6 | 0.00% | 0 / 1 | 5.12 | ||
| [Lucent\Validation\Constraint] withMessage | 100.00% | 2 / 2 | 100.00% | 1 / 1 | 1 | ||
| [Lucent\Validation\Constraint] message | 100.00% | 6 / 6 | 100.00% | 1 / 1 | 3 | ||
| 17 | final class Required extends Constraint | |
| 18 | { | |
| 19 | /** | |
| 20 | * @return string|Closure(FieldContext): string The default error message. | |
| 21 | */ | |
| 22 | #[Override] | |
| 23 | protected function defaultMessage(): string|Closure|null | |
| 24 | { | |
| 25 | return fn(FieldContext $ctx) => "The {$ctx->field} is required."; | |
| 26 | } | |
| 27 | ||
| 28 | /** | |
| 29 | * Validate that the field has a non-empty value. | |
| 30 | * | |
| 31 | * Null, empty strings, and empty arrays are all considered missing. | |
| 32 | * | |
| 33 | * @param FieldContext $ctx The context of the field being validated. | |
| 34 | * @return bool True if the value is present, false otherwise. | |
| 35 | */ | |
| 36 | #[Override] | |
| 37 | public function validate(FieldContext $ctx): bool | |
| 38 | { | |
| 39 | $value = $ctx->value; | |
| 40 | ||
| 41 | // null and empty string are missing. | |
| 42 | if ($value === null || $value === '') { | |
| 43 | return false; | |
| 44 | } | |
| 45 | ||
| 46 | // An empty array is missing. | |
| 47 | if (is_array($value) && $value === []) { | |
| 48 | return false; | |
| 49 | } | |
| 50 | ||
| 51 | return true; | |
| 52 | } | |
| 53 | } |
Inherited from Lucent\Validation\Constraint
| 38 | final public function withMessage(string|\Closure $message): static | |
| 39 | { | |
| 40 | $this->customMessage = $message; | |
| 41 | return $this; | |
| 42 | } |
| 56 | final public function message(FieldContext $ctx): ?string | |
| 57 | { | |
| 58 | $message = $this->customMessage ?? $this->defaultMessage(); | |
| 59 | ||
| 60 | if ($message === null) { | |
| 61 | return null; | |
| 62 | } | |
| 63 | ||
| 64 | if ($message instanceof \Closure) { | |
| 65 | return call_user_func($message, $ctx); | |
| 66 | } | |
| 67 | ||
| 68 | return $message; | |
| 69 | } |