Lines 100.00% 27 / 27
Methods 100.00% 4 / 4
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 defaultMessage 100.00% 1 / 1 100.00% 1 / 1 1
 validate 100.00% 18 / 18 100.00% 1 / 1 9
 [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
21final class Boolean extends Constraint
22{
23    /**
24     * @return string|Closure(FieldContext): string The default error message.
25     */
26    #[Override]
27    protected function defaultMessage(): string|Closure|null
28    {
29        return fn(FieldContext $ctx) => "The {$ctx->field} must be a boolean.";
30    }
31
32    /**
33     * Validate and normalize a boolean value.
34     *
35     * Real booleans pass as-is. The strings `'true'`/`'1'` and
36     * `'false'`/`'0'` (case-insensitive for the word forms) and the integers
37     * `1`/`0` are normalized to a real boolean. Any other value fails.
38     *
39     * @param FieldContext $ctx The context of the field being validated.
40     * @return bool True if the value is a valid boolean representation, false otherwise.
41     */
42    #[Override]
43    public function validate(FieldContext $ctx): bool
44    {
45        $value = $ctx->value;
46
47        if (is_bool($value)) {
48            return true;
49        }
50
51        if ($value === 1 || $value === '1') {
52            $ctx->normalize(true);
53            return true;
54        }
55
56        if ($value === 0 || $value === '0') {
57            $ctx->normalize(false);
58            return true;
59        }
60
61        if (is_string($value)) {
62            $normalized = strtolower($value);
63
64            if ($normalized === 'true') {
65                $ctx->normalize(true);
66                return true;
67            }
68
69            if ($normalized === 'false') {
70                $ctx->normalize(false);
71                return true;
72            }
73        }
74
75        return false;
76    }
77}

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    }