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

RegularExpressionValidator::init()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 3
nop 0
crap 3
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\validators;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
13
/**
14
 * RegularExpressionValidator validates that the attribute value matches the specified [[pattern]].
15
 *
16
 * If the [[not]] property is set true, the validator will ensure the attribute value do NOT match the [[pattern]].
17
 *
18
 * @author Qiang Xue <[email protected]>
19
 * @since 2.0
20
 */
21
class RegularExpressionValidator extends Validator
22
{
23
    /**
24
     * @var string the regular expression to be matched with
25
     */
26
    public $pattern;
27
    /**
28
     * @var bool whether to invert the validation logic. Defaults to false. If set to true,
29
     * the regular expression defined via [[pattern]] should NOT match the attribute value.
30
     */
31
    public $not = false;
32
33
34
    /**
35
     * @inheritdoc
36
     */
37 4
    public function init()
38
    {
39 4
        parent::init();
40 4
        if ($this->pattern === null) {
41 1
            throw new InvalidConfigException('The "pattern" property must be set.');
42
        }
43 3
        if ($this->message === null) {
44 3
            $this->message = Yii::t('yii', '{attribute} is invalid.');
45
        }
46 3
    }
47
48
    /**
49
     * @inheritdoc
50
     */
51 2
    protected function validateValue($value)
52
    {
53 2
        $valid = !is_array($value) &&
54 2
            (!$this->not && preg_match($this->pattern, $value)
55 2
            || $this->not && !preg_match($this->pattern, $value));
56
57 2
        return $valid ? null : [$this->message, []];
58
    }
59
}
60