Passed
Pull Request — master (#19663)
by Alexander
08:07
created

UrlValidator::isEmpty()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
nc 3
nop 1
dl 0
loc 7
ccs 0
cts 4
cp 0
crap 12
rs 10
c 1
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\validators;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\Json;
13
use yii\web\JsExpression;
14
15
/**
16
 * UrlValidator validates that the attribute value is a valid http or https URL.
17
 *
18
 * Note that this validator only checks if the URL scheme and host part are correct.
19
 * It does not check the remaining parts of a URL.
20
 *
21
 * @author Qiang Xue <[email protected]>
22
 * @since 2.0
23
 */
24
class UrlValidator extends Validator
25
{
26
    /**
27
     * @var string the regular expression used to validate the attribute value.
28
     * The pattern may contain a `{schemes}` token that will be replaced
29
     * by a regular expression which represents the [[validSchemes]].
30
     */
31
    public $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
    public $validSchemes = ['http', 'https'];
37
    /**
38
     * @var string|null the default URI scheme. If the input doesn't contain the scheme part, the default
39
     * scheme will be prepended to it (thus changing the input). Defaults to null, meaning a URL must
40
     * contain the scheme part.
41
     */
42
    public $defaultScheme;
43
    /**
44
     * @var bool whether validation process should take into account IDN (internationalized
45
     * domain names). Defaults to false meaning that validation of URLs containing IDN will always
46
     * fail. Note that in order to use IDN validation you have to install and enable `intl` PHP
47
     * extension, otherwise an exception would be thrown.
48
     */
49
    public $enableIDN = false;
50
51
52
    /**
53
     * {@inheritdoc}
54
     */
55 7
    public function init()
56
    {
57 7
        parent::init();
58 7
        if ($this->enableIDN && !function_exists('idn_to_ascii')) {
59
            throw new InvalidConfigException('In order to use IDN validation intl extension must be installed and enabled.');
60
        }
61 7
        if ($this->message === null) {
62 7
            $this->message = Yii::t('yii', '{attribute} is not a valid URL.');
63
        }
64 7
    }
65
66
    /**
67
     * {@inheritdoc}
68
     */
69 1
    public function validateAttribute($model, $attribute)
70
    {
71 1
        $value = $model->$attribute;
72 1
        $result = $this->validateValue($value);
73 1
        if (!empty($result)) {
74 1
            $this->addError($model, $attribute, $result[0], $result[1]);
75 1
        } elseif ($this->defaultScheme !== null && strpos($value, '://') === false) {
76 1
            $model->$attribute = $this->defaultScheme . '://' . $value;
77
        }
78 1
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83 7
    protected function validateValue($value)
84
    {
85
        // make sure the length is limited to avoid DOS attacks
86 7
        if (is_string($value) && strlen($value) < 2000) {
87 6
            if ($this->defaultScheme !== null && strpos($value, '://') === false) {
88 3
                $value = $this->defaultScheme . '://' . $value;
89
            }
90
91 6
            if (strpos($this->pattern, '{schemes}') !== false) {
92 5
                $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
93
            } else {
94 1
                $pattern = $this->pattern;
95
            }
96
97 6
            if ($this->enableIDN) {
98 1
                $value = preg_replace_callback('/:\/\/([^\/]+)/', function ($matches) {
99 1
                    return '://' . $this->idnToAscii($matches[1]);
100 1
                }, $value);
101
            }
102
103 6
            if (preg_match($pattern, $value)) {
104 6
                return null;
105
            }
106
        }
107
108 4
        return [$this->message, []];
109
    }
110
111 1
    private function idnToAscii($idn)
112
    {
113 1
        if (PHP_VERSION_ID < 50600) {
114
            // TODO: drop old PHP versions support
115
            return idn_to_ascii($idn);
116
        }
117
118 1
        return idn_to_ascii($idn, IDNA_NONTRANSITIONAL_TO_ASCII, INTL_IDNA_VARIANT_UTS46);
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function clientValidateAttribute($model, $attribute, $view)
125
    {
126
        ValidationAsset::register($view);
127
        if ($this->enableIDN) {
128
            PunycodeAsset::register($view);
129
        }
130
        $options = $this->getClientOptions($model, $attribute);
131
132
        return 'yii.validation.url(value, messages, ' . Json::htmlEncode($options) . ');';
133
    }
134
135
    /**
136
     * {@inheritdoc}
137
     */
138
    public function getClientOptions($model, $attribute)
139
    {
140
        if (strpos($this->pattern, '{schemes}') !== false) {
141
            $pattern = str_replace('{schemes}', '(' . implode('|', $this->validSchemes) . ')', $this->pattern);
142
        } else {
143
            $pattern = $this->pattern;
144
        }
145
146
        $options = [
147
            'pattern' => new JsExpression($pattern),
148
            'message' => $this->formatMessage($this->message, [
149
                'attribute' => $model->getAttributeLabel($attribute),
150
            ]),
151
            'enableIDN' => (bool) $this->enableIDN,
152
        ];
153
        if ($this->skipOnEmpty) {
154
            $options['skipOnEmpty'] = 1;
155
        }
156
        if ($this->defaultScheme !== null) {
157
            $options['defaultScheme'] = $this->defaultScheme;
158
        }
159
160
        return $options;
161
    }
162
163
    /**
164
     * {@inheritdoc}
165
     */
166
    public function isEmpty($value)
167
    {
168
        if ($this->isEmpty !== null) {
169
            return call_user_func($this->isEmpty, $value);
170
        }
171
172
        return $value === null || $value === '';
173
    }
174
}
175