Completed
Branch master (a1edd4)
by
unknown
54:09
created

validateValue()   C

Complexity

Conditions 15
Paths 132

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 6.4166
c 0
b 0
f 0
cc 15
eloc 15
nc 132
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * This file is part of the fangface/yii2-concord package
4
 *
5
 * For the full copyright and license information, please view
6
 * the file LICENSE.md that was distributed with this source code.
7
 *
8
 * @package fangface/yii2-concord
9
 * @author Fangface <[email protected]>
10
 * @copyright Copyright (c) 2014 Fangface <[email protected]>
11
 * @license https://github.com/fangface/yii2-concord/blob/master/LICENSE.md MIT License
12
 *
13
 */
14
15
namespace fangface\validators;
16
17
use Yii;
18
use yii\base\InvalidConfigException;
19
use yii\helpers\Html;
20
use yii\web\JsExpression;
21
use yii\helpers\Json;
22
use yii\validators\Validator;
23
use yii\validators\ValidationAsset;
24
25
/**
26
 * ConditionalRegularExpressionValidator validates that the attribute value matches the specified [[pattern]].
27
 *
28
 * If the [[not]] property is set true, the validator will ensure the attribute value do NOT match the [[pattern]].
29
 *
30
 * Once the validation is performed a subsequent [[patternFail]] or [[patternPass]] pattern match will be perfomed
31
 * accordingly
32
 *
33
 * If [[patternPass]] should be run on [[pattern]] passing, leaving [[patternFail]] unused in the event of
34
 * [[pattern]] failing then simply setting [[patternFail]] to false will achieve this
35
 */
36
class ConditionalRegularExpressionValidator extends Validator
37
{
38
    /**
39
     * @var string the regular expression to be matched with
40
     */
41
    public $pattern;
42
    /**
43
     * @var boolean whether to invert the validation logic. Defaults to false. If set to true,
44
     * the regular expression defined via [[pattern]] should NOT match the attribute value.
45
     */
46
    public $not = false;
47
    /**
48
     * @var string the regular expression to be matched with when passing the conditional pattern
49
     */
50
    public $patternOnPass;
51
    /**
52
     * @var boolean whether to invert the validation logic. Defaults to false. If set to true,
53
     * the regular expression defined via [[patternOnPass]] should NOT match the attribute value.
54
     */
55
    public $notOnPass = false;
56
    /**
57
     * @var string the error message to use if [[patternOnPass]] is used and successfully matched
58
     */
59
    public $messageOnPass;
60
    /**
61
     * @var string the regular expression to be matched with when failing the conditional pattern
62
     */
63
    public $patternOnFail;
64
    /**
65
     * @var boolean whether to invert the validation logic. Defaults to false. If set to true,
66
     * the regular expression defined via [[patternOnFail]] should NOT match the attribute value.
67
     */
68
    public $notOnFail = false;
69
    /**
70
     * @var string the error message to use if [[patternOnFail]] is used and successfully matched
71
     */
72
    public $messageOnFail = '';
73
74
75
    /**
76
     * @inheritdoc
77
     */
78
    public function init()
79
    {
80
        parent::init();
81
        if ($this->pattern === null) {
82
            throw new InvalidConfigException('The "pattern" property must be set.');
83
        }
84
        if ($this->patternOnPass === null) {
85
            throw new InvalidConfigException('The "patternOnPass" property must be set.');
86
        }
87
        if ($this->patternOnFail === null) {
88
            throw new InvalidConfigException('The "patternOnPass" property must be set.');
89
        }
90
        if ($this->messageOnPass === null) {
91
            $this->messageOnPass = Yii::t('yii', '{attribute} is invalid.');
92
        }
93
        if ($this->messageOnFail === null) {
94
            $this->messageOnFail = Yii::t('yii', '{attribute} is invalid.');
95
        }
96
    }
97
98
    /**
99
     * @inheritdoc
100
     */
101
    protected function validateValue($value)
102
    {
103
        $valid = !is_array($value) &&
104
            (!$this->not && preg_match($this->pattern, $value)
105
            || $this->not && !preg_match($this->pattern, $value));
106
107
        if ($valid) {
108
            $valid = (!$this->notOnPass && preg_match($this->patternOnPass, $value)
109
                || $this->notOnPass && !preg_match($this->patternOnPass, $value));
110
            return $valid ? null : [$this->messageOnPass, []];
111
        } else {
112
            if ($this->patternOnFail === false) {
113
                $valid = true;
114
            } else {
115
                $valid = (!$this->notOnFail && preg_match($this->patternOnFail, $value)
116
                    || $this->notOnFail && !preg_match($this->patternOnFail, $value));
117
            }
118
            return $valid ? null : [$this->messageOnFail, []];
119
        }
120
    }
121
122
    /**
123
     * @inheritdoc
124
     */
125
    public function clientValidateAttribute($model, $attribute, $view)
126
    {
127
        $pattern = Html::escapeJsRegularExpression($this->pattern);
0 ignored issues
show
Bug introduced by
The method escapeJsRegularExpression() does not seem to exist on object<yii\helpers\Html>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
128
        $options = [
129
            'pattern' => new JsExpression($pattern),
130
            'not' => $this->not,
131
        ];
132
        if ($this->skipOnEmpty) {
133
            $options['skipOnEmpty'] = 1;
134
        }
135
136
        $pattern = Html::escapeJsRegularExpression($this->patternOnPass);
0 ignored issues
show
Bug introduced by
The method escapeJsRegularExpression() does not seem to exist on object<yii\helpers\Html>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
137
        $optionsPass = [
138
            'pattern' => new JsExpression($pattern),
139
            'not' => $this->notOnPass,
140
            'message' => Yii::$app->getI18n()->format($this->messageOnPass, [
141
                'attribute' => $model->getAttributeLabel($attribute),
142
            ], Yii::$app->language),
143
        ];
144
        if ($this->skipOnEmpty) {
145
            $optionsPass['skipOnEmpty'] = 1;
146
        }
147
148
        if ($this->patternOnFail === false) {
149
            $optionsFail = false;
150
        } else {
151
            $pattern = Html::escapeJsRegularExpression($this->patternOnFail);
0 ignored issues
show
Bug introduced by
The method escapeJsRegularExpression() does not seem to exist on object<yii\helpers\Html>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
152
            $optionsFail = [
153
                'pattern' => new JsExpression($pattern),
154
                'not' => $this->notOnFail,
155
                'message' => Yii::$app->getI18n()->format($this->messageOnFail, [
156
                    'attribute' => $model->getAttributeLabel($attribute),
157
                ], Yii::$app->language),
158
            ];
159
            if ($this->skipOnEmpty) {
160
                $optionsFail['skipOnEmpty'] = 1;
161
            }
162
        }
163
164
        ValidationAsset::register($view);
165
166
        return 'localAppValidation.conditionalRegExp(value, messages, ' . Json::htmlEncode($options) . ', ' . Json::htmlEncode($optionsPass) . ', ' . Json::htmlEncode($optionsFail) . ');';
0 ignored issues
show
Bug introduced by
The method htmlEncode() does not exist on yii\helpers\Json. Did you maybe mean encode()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
167
    }
168
}
169