respect-validation/tests/unit/Validators/UrlTest.php
Alexandre Gomes Gaigalas a64e33168f Improve Url validator to be more strict
Previously, the URL validator accepted all kinds of URLs.

Combining it with other validators like `Domain` and `Ip` manually
is clumbersome, since the rules are extensive and require small
tweaks such as understanding bracketed IP addresses.

This change makes that composition built-in. The validator still
uses the FILTER_VALIDATE_URL from PHP, but now it also goes deeper
and validate portions of the URL that other validators support.

Changes to `Call` were made so that it can be serialized under
certain circumstances (when invoking a static method call), making
it more flexible.

A static internal method helper for trimming the IP was added to
the Url validator class and marked as internal, as it cannot be
both private, serializable and accessible to the `Call` instance
all at the same time. The `@internal` annotation should advise
users that it's not a public API according to phpdoc conventions.
2026-02-02 00:26:40 +00:00

58 lines
2.1 KiB
PHP

<?php
/*
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-FileContributor: Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-FileContributor: Gabriel Caruso <carusogabriel34@gmail.com>
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/
declare(strict_types=1);
namespace Respect\Validation\Validators;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
use Respect\Validation\Test\RuleTestCase;
#[Group('validator')]
#[CoversClass(Url::class)]
final class UrlTest extends RuleTestCase
{
/** @return iterable<array{Url, mixed}> */
public static function providerForValidInput(): iterable
{
$validator = new Url();
return [
[$validator, 'ftp://ftp.is.co.za.example.org/rfc/rfc1808.txt'],
[$validator, 'gopher://spinaltap.micro.umn.example.edu/00/Weather/California/Los%20Angeles'],
[$validator, 'http://www.ietf.org/rfc/rfc2396.txt'],
[$validator, 'http://www.math.uio.no.example.net/faq/compression-faq/part1.html'],
[$validator, 'https://www.youtube.com/watch?v=6FOUqQt3Kg0'],
[$validator, 'ldap://[2001:db8::7]/c=GB?objectClass?one'],
[$validator, 'mailto:John.Doe@example.com'],
[$validator, 'mailto:mduerst@ifi.unizh.example.gov'],
[$validator, 'telnet://192.0.2.16:80/'],
[$validator, 'telnet://melvyl.ucop.example.edu/'],
];
}
/** @return iterable<array{Url, mixed}> */
public static function providerForInvalidInput(): iterable
{
$validator = new Url();
return [
[$validator, 'example.com'],
[$validator, 'news:comp.infosystems.www.servers.unix'],
[$validator, 'news:comp.infosystems.www.servers.unix'],
[$validator, 'mailto:not_an_actual_email'],
[$validator, 'https://example.this_tld_is_invalid'],
[$validator, 'http:/example.com/'],
[$validator, 'tel:+1-816-555-1212'],
[$validator, 'urn:oasis:names:specification:docbook:dtd:xml:4.1.2'],
];
}
}