Lines 100.00% 14 / 14
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% 4 / 4 100.00% 1 / 1 3
 [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 Uri extends Constraint
19{
20    /**
21     * Create a URI constraint.
22     *
23     * @param int $flags Validation flags for {@see MessageUri::isValid()}.
24     */
25    public function __construct(private readonly int $flags = MessageUri::VALIDATE_DEFAULT) {}
26
27    /**
28     * @return string|Closure(FieldContext): string The default error message.
29     */
30    #[Override]
31    protected function defaultMessage(): string|Closure|null
32    {
33        return fn(FieldContext $ctx) => "The {$ctx->field} must be a valid URI.";
34    }
35
36    /**
37     * Validate that the value is a valid URI.
38     *
39     * On success the value is normalized to a {@see MessageUri} instance.
40     *
41     * @param FieldContext $ctx The context of the field being validated.
42     * @return bool True if the value is a valid URI, false otherwise.
43     */
44    #[Override]
45    public function validate(FieldContext $ctx): bool
46    {
47        if (!is_string($ctx->value) || !MessageUri::isValid($ctx->value, $this->flags)) {
48            return false;
49        }
50
51        $ctx->normalize(MessageUri::fromString($ctx->value));
52        return true;
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    }