Passed
Push — master ( b43541...841b5a )
by Alexander
28:36 queued 27:17
created

Url::message()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 0
cts 4
cp 0
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 5
    public function __construct()
44
    {
45 5
        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 5
    protected function validateValue($value, DataSetInterface $dataSet = null): Result
51
    {
52 5
        $result = new Result();
53
54
        // make sure the length is limited to avoid DOS attacks
55 5
        if (is_string($value) && strlen($value) < 2000) {
56 4
            if (strpos($this->pattern, '{schemes}') !== false) {
57 3
                $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
58
            } else {
59 1
                $pattern = $this->pattern;
60
            }
61
62 4
            if ($this->enableIDN) {
63 1
                $value = preg_replace_callback(
64 1
                    '/:\/\/([^\/]+)/',
65
                    function ($matches) {
66 1
                        return '://' . $this->idnToAscii($matches[1]);
67 1
                    },
68
                    $value
69
                );
70
            }
71
72 4
            if (preg_match($pattern, $value)) {
73 4
                return $result;
74
            }
75
        }
76
77 3
        $result->addError($this->translateMessage($this->message));
78
79 3
        return $result;
80
    }
81
82 1
    private function idnToAscii($idn)
83
    {
84 1
        return idn_to_ascii($idn, 0, INTL_IDNA_VARIANT_UTS46);
85
    }
86
87 1
    public function pattern(string $pattern): self
88
    {
89 1
        $new = clone $this;
90 1
        $new->pattern = $pattern;
91 1
        return $new;
92
    }
93
94 1
    public function enableIDN(): self
95
    {
96 1
        $new = clone $this;
97 1
        $new->enableIDN = true;
98 1
        return $new;
99
    }
100
101 1
    public function schemes(array $schemes): self
102
    {
103 1
        $new = clone $this;
104 1
        $new->validSchemes = $schemes;
105 1
        return $new;
106
    }
107
}
108