Completed
Push — master ( b9dd81...933d7a )
by Dmitry
06:41
created

DomainValidator::convertIdnToAscii()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * HiPanel core package
5
 *
6
 * @link      https://hipanel.com/
7
 * @package   hipanel-core
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2014-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\validators;
13
14
use Yii;
15
use yii\validators\PunycodeAsset;
16
17
/**
18
 * Class DomainValidator is used to validate domain names with a regular expression.
19
 */
20
class DomainValidator extends \yii\validators\RegularExpressionValidator
21
{
22
    /**
23
     * {@inheritdoc}
24
     */
25
    public $pattern = '/^([a-z0-9][a-z0-9-]*\.)+[a-z0-9][a-z0-9-]*$/';
26
27
    /**
28
     * @var bool
29
     */
30
    public $enableIdn = false;
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function init()
36
    {
37
        parent::init();
38
        if ($this->message === null) {
39
            $this->message = Yii::t('hipanel', '{attribute} does not look like a valid domain name');
40
        }
41
    }
42
43
    /**
44
     * @inheritdoc
45
     */
46
    public function validateAttribute($model, $attribute)
47
    {
48
        if ($this->enableIdn) {
49
            $model->$attribute = idn_to_ascii($model->$attribute);
50
        }
51
52
        parent::validateAttribute($model, $attribute);
53
    }
54
55
    /**
56
     * @param string $value the IDN domain name that should be converted to ASCII
57
     * @return string
58
     */
59
    public function convertIdnToAscii($value)
60
    {
61
        return idn_to_ascii($value);
62
    }
63
64
    public function convertAsciiToIdn($value)
65
    {
66
        return idn_to_utf8($value);
67
    }
68
69
70
    public function clientValidateAttribute($model, $attribute, $view)
71
    {
72
        $js = parent::clientValidateAttribute($model, $attribute, $view);
73
        if (!$this->enableIdn) {
74
            return $js;
75
        }
76
77
        PunycodeAsset::register($view);
78
79
        return "value = punycode.toASCII(value); $js";
80
    }
81
82
}
83