Passed
Push — master ( a9d357...8e355c )
by Alexander
02:33
created

Url::convertIdn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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