forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUrl.php
More file actions
70 lines (59 loc) · 1.93 KB
/
Copy pathUrl.php
File metadata and controls
70 lines (59 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/*
* SPDX-License-Identifier: MIT
* SPDX-FileCopyrightText: (c) Respect Project Contributors
* SPDX-FileContributor: Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-FileContributor: Henrique Moody <henriquemoody@gmail.com>
*/
declare(strict_types=1);
namespace Respect\Validation\Validators;
use Attribute;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Validator;
use function filter_var;
use function trim;
use const FILTER_VALIDATE_URL;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must be a valid URL',
'{{subject}} must not be a valid URL',
)]
final class Url implements Validator
{
private readonly Validator $validator;
public function __construct()
{
$this->validator = new Call(
'parse_url',
new Circuit(
new ArrayType(),
new OneOf(
new Circuit(
new Key('scheme', new In(['http', 'https', 'ftp', 'telnet', 'gopher', 'ldap'])),
new Key('host', new OneOf(
new Domain(),
new Call([self::class, 'formatIp'], new Ip()),
)),
),
new Circuit(
new Key('scheme', new Equals('mailto')),
new Key('path', new Email()),
),
),
),
);
}
public function evaluate(mixed $input): Result
{
if (!filter_var($input, FILTER_VALIDATE_URL)) {
return Result::failed($input, $this);
}
return Result::of($this->validator->evaluate($input)->hasPassed, $input, $this, []);
}
/** @internal public so it can be accessed by unserialized instance */
public static function formatIp(string $ip): string
{
return trim($ip, '[]');
}
}