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