Completed
Push — 2.1 ( 75349f...bf116e )
by Alexander
29:27
created

UrlValidator::getClientOptions()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 0
cts 22
cp 0
rs 8.6845
c 0
b 0
f 0
cc 4
eloc 15
nc 8
nop 3
crap 20
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\jquery\validators\client;
9
10
use yii\helpers\Json;
11
use yii\jquery\PunycodeAsset;
12
use yii\jquery\ValidationAsset;
13
use yii\validators\client\ClientValidator;
14
use yii\web\JsExpression;
15
16
/**
17
 * UrlValidator composes client-side validation code from [[\yii\validators\UrlValidator]].
18
 *
19
 * @see \yii\validators\UrlValidator
20
 * @see ValidationAsset
21
 *
22
 * @author Paul Klimov <[email protected]>
23
 * @since 2.1.0
24
 */
25
class UrlValidator extends ClientValidator
26
{
27
    /**
28
     * @inheritdoc
29
     */
30
    public function build($validator, $model, $attribute, $view)
31
    {
32
        /* @var $validator \yii\validators\UrlValidator */
33
        ValidationAsset::register($view);
34
        if ($validator->enableIDN) {
35
            PunycodeAsset::register($view);
36
        }
37
        $options = $this->getClientOptions($validator, $model, $attribute);
38
        return 'yii.validation.url(value, messages, ' . Json::htmlEncode($options) . ');';
39
    }
40
41
    /**
42
     * Returns the client-side validation options.
43
     * @param \yii\validators\UrlValidator $validator the server-side validator.
44
     * @param \yii\base\Model $model the model being validated
45
     * @param string $attribute the attribute name being validated
46
     * @return array the client-side validation options
47
     */
48
    public function getClientOptions($validator, $model, $attribute)
49
    {
50
        if (strpos($validator->pattern, '{schemes}') !== false) {
51
            $pattern = str_replace('{schemes}', '(' . implode('|', $validator->validSchemes) . ')', $validator->pattern);
52
        } else {
53
            $pattern = $validator->pattern;
54
        }
55
56
        $options = [
57
            'pattern' => new JsExpression($pattern),
58
            'message' => $validator->formatMessage($validator->message, [
59
                'attribute' => $model->getAttributeLabel($attribute),
60
            ]),
61
            'enableIDN' => (bool) $validator->enableIDN,
62
        ];
63
        if ($validator->skipOnEmpty) {
64
            $options['skipOnEmpty'] = 1;
65
        }
66
        if ($validator->defaultScheme !== null) {
67
            $options['defaultScheme'] = $validator->defaultScheme;
68
        }
69
70
        return $options;
71
    }
72
}