Passed
Pull Request — master (#122)
by
unknown
02:35
created

Url::enableIDN()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 2
b 0
f 0
nc 2
nop 0
dl 0
loc 9
ccs 5
cts 6
cp 0.8333
crap 2.0185
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\HasValidationErrorMessage;
8
use Yiisoft\Validator\Result;
9
use Yiisoft\Validator\Rule;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function function_exists;
13
use function is_string;
14
use function strlen;
15
16
/**
17
 * UrlValidator validates that the attribute value is a valid HTTP or HTTPS URL.
18
 *
19
 * Note that this validator only checks if the URL scheme and host part are correct.
20
 * It does not check the remaining parts of a URL.
21
 */
22
class Url extends Rule
23
{
24
    use HasValidationErrorMessage;
25
26
    /**
27
     * @var string the regular expression used to validateValue the attribute value.
28
     * The pattern may contain a `{schemes}` token that will be replaced
29
     * by a regular expression which represents the {@see schemes()}.
30
     */
31
    private string $pattern = '/^{schemes}:\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(?::\d{1,5})?(?:$|[?\/#])/i';
32
    /**
33
     * @var array list of URI schemes which should be considered valid. By default, http and https
34
     * are considered to be valid schemes.
35
     */
36
    private array $validSchemes = ['http', 'https'];
37
    /**
38
     * @var bool whether validation process should take into account IDN (internationalized
39
     * domain names). Defaults to false meaning that validation of URLs containing IDN will always
40
     * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
41
     * extension, otherwise an exception would be thrown.
42
     */
43
    private bool $enableIDN = false;
44
45
    private string $message = 'This value is not a valid URL.';
46
47 9
    protected function validateValue($value, ValidationContext $context = null): Result
48
    {
49 9
        $result = new Result();
50
51
        // make sure the length is limited to avoid DOS attacks
52 9
        if (is_string($value) && strlen($value) < 2000) {
53 8
            if ($this->enableIDN) {
54 5
                $value = $this->convertIdn($value);
55
            }
56
57 8
            if (preg_match($this->getPattern(), $value)) {
58 6
                return $result;
59
            }
60
        }
61
62 5
        $result->addError($this->formatMessage($this->message));
63
64 5
        return $result;
65
    }
66
67 5
    private function idnToAscii($idn)
68
    {
69 5
        return idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
70
    }
71
72 5
    private function convertIdn($value): string
73
    {
74 5
        if (strpos($value, '://') === false) {
75 3
            return $this->idnToAscii($value);
76
        }
77
78 2
        return preg_replace_callback(
79 2
            '/:\/\/([^\/]+)/',
80 2
            fn ($matches) => '://' . $this->idnToAscii($matches[1]),
81
            $value
82
        );
83
    }
84
85 8
    private function getPattern(): string
86
    {
87 8
        if (strpos($this->pattern, '{schemes}') !== false) {
88 6
            return str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
89
        }
90
91 2
        return $this->pattern;
92
    }
93
94 2
    public function pattern(string $pattern): self
95
    {
96 2
        $new = clone $this;
97 2
        $new->pattern = $pattern;
98 2
        return $new;
99
    }
100
101 7
    public function enableIDN(): self
102
    {
103 7
        if (!function_exists('idn_to_ascii')) {
104
            throw new \RuntimeException('In order to use IDN validation intl extension must be installed and enabled.');
105
        }
106
107 7
        $new = clone $this;
108 7
        $new->enableIDN = true;
109 7
        return $new;
110
    }
111
112 1
    public function schemes(array $schemes): self
113
    {
114 1
        $new = clone $this;
115 1
        $new->validSchemes = $schemes;
116 1
        return $new;
117
    }
118
119 6
    public function getOptions(): array
120
    {
121 6
        return array_merge(
122 6
            parent::getOptions(),
123
            [
124 6
                'message' => $this->formatMessage($this->message),
125 6
                'enableIDN' => $this->enableIDN,
126 6
                'validSchemes' => $this->validSchemes,
127 6
                'pattern' => $this->pattern,
128
            ],
129
        );
130
    }
131
}
132