Passed
Push — master ( 2b6758...acf834 )
by Aleksei
06:59
created

Url::getOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Rule;
6
7
use Yiisoft\Validator\DataSetInterface;
8
use Yiisoft\Validator\HasValidationErrorMessage;
9
use Yiisoft\Validator\Result;
10
use Yiisoft\Validator\Rule;
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 HasValidationErrorMessage;
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 13
    public function __construct()
44
    {
45 13
        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 13
    }
49
50 9
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
51
    {
52 9
        $result = new Result();
53
54
        // make sure the length is limited to avoid DOS attacks
55 9
        if (is_string($value) && strlen($value) < 2000) {
56 8
            if ($this->enableIDN) {
57 5
                $value = $this->convertIdn($value);
58
            }
59
60 8
            if (preg_match($this->getPattern(), $value)) {
61 6
                return $result;
62
            }
63
        }
64
65 5
        $result->addError($this->translateMessage($this->message));
66
67 5
        return $result;
68
    }
69
70 5
    private function idnToAscii($idn)
71
    {
72 5
        return idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
73
    }
74
75 5
    private function convertIdn($value): string
76
    {
77 5
        if (strpos($value, '://') === false) {
78 3
            return $this->idnToAscii($value);
79
        }
80
81 2
        return preg_replace_callback(
82 2
            '/:\/\/([^\/]+)/',
83 2
            fn ($matches) => '://' . $this->idnToAscii($matches[1]),
84
            $value
85
        );
86
    }
87
88 8
    private function getPattern(): string
89
    {
90 8
        if (strpos($this->pattern, '{schemes}') !== false) {
91 6
            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 8
    public function enableIDN(): self
105
    {
106 8
        $new = clone $this;
107 8
        $new->enableIDN = true;
108 8
        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 7
    public function getOptions(): array
119
    {
120 7
        return array_merge(
121 7
            parent::getOptions(),
122
            [
123 7
                'message' => $this->translateMessage($this->message),
124 7
                'enableIDN' => $this->enableIDN,
125 7
                'validSchemes' => $this->validSchemes,
126 7
                'pattern' => $this->pattern,
127
            ],
128
        );
129
    }
130
}
131