Lines 100.00% 12 / 12
Methods 100.00% 5 / 5
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 defaultMessage 100.00% 1 / 1 100.00% 1 / 1 1
 validate 100.00% 2 / 2 100.00% 1 / 1 2
 [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
18final class Ip extends Constraint
19{
20    /** Restrict validation to IPv4 addresses. */
21    public const IPV4 = FILTER_FLAG_IPV4;
22
23    /** Restrict validation to IPv6 addresses. */
24    public const IPV6 = FILTER_FLAG_IPV6;
25
26    /**
27     * Create an IP address constraint.
28     *
29     * @param int $flags Optional filter flags, e.g. {@see Ip::IPV4} or {@see Ip::IPV6}.
30     */
31    public function __construct(private readonly int $flags = 0) {}
32
33    /**
34     * @return string|Closure(FieldContext): string The default error message.
35     */
36    #[Override]
37    protected function defaultMessage(): string|Closure|null
38    {
39        return fn(FieldContext $ctx) => "The {$ctx->field} must be a valid IP address.";
40    }
41
42    /**
43     * Validate that the value is a valid IP address.
44     *
45     * @param FieldContext $ctx The context of the field being validated.
46     * @return bool True if the value is a valid IP address, false otherwise.
47     */
48    #[Override]
49    public function validate(FieldContext $ctx): bool
50    {
51        return is_string($ctx->value)
52            && filter_var($ctx->value, FILTER_VALIDATE_IP, $this->flags) !== false;
53    }
54}

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    }