forked from Respect/Validation
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDomain.php
More file actions
95 lines (79 loc) · 2.47 KB
/
Domain.php
File metadata and controls
95 lines (79 loc) · 2.47 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
/*
* Copyright (c) Alexandre Gomes Gaigalas <alganet@gmail.com>
* SPDX-License-Identifier: MIT
*/
declare(strict_types=1);
namespace Respect\Validation\Rules;
use Attribute;
use Respect\Validation\Message\Template;
use Respect\Validation\Result;
use Respect\Validation\Rule;
use function array_pop;
use function count;
use function explode;
use function mb_substr_count;
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
#[Template(
'{{subject}} must be a valid domain',
'{{subject}} must not be a valid domain',
)]
final class Domain implements Rule
{
private readonly Rule $genericRule;
private readonly Rule $tldRule;
private readonly Rule $partsRule;
public function __construct(bool $tldCheck = true)
{
$this->genericRule = $this->createGenericRule();
$this->tldRule = $this->createTldRule($tldCheck);
$this->partsRule = $this->createPartsRule();
}
public function evaluate(mixed $input): Result
{
$genericResult = $this->genericRule->evaluate($input);
if (!$genericResult->hasPassed) {
return Result::failed($input, $this);
}
$parts = explode('.', (string) $input);
if (count($parts) >= 2) {
$childResult = $this->tldRule->evaluate(array_pop($parts));
if (!$childResult->hasPassed) {
return Result::failed($input, $this);
}
}
return Result::of($this->partsRule->evaluate($parts)->hasPassed, $input, $this);
}
private function createGenericRule(): Circuit
{
return new Circuit(
new StringType(),
new NoWhitespace(),
new Contains('.'),
new Length(new GreaterThanOrEqual(3)),
);
}
private function createTldRule(bool $realTldCheck): Rule
{
if ($realTldCheck) {
return new Tld();
}
return new Circuit(new Not(new StartsWith('-')), new Length(new GreaterThanOrEqual(2)));
}
private function createPartsRule(): Rule
{
return new Each(
new Circuit(
new Alnum('-'),
new Not(new StartsWith('-')),
new AnyOf(
new Not(new Contains('--')),
new Callback(static function ($str) {
return mb_substr_count($str, '--') == 1;
}),
),
new Not(new EndsWith('-')),
),
);
}
}