RuleParser   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 192
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 4
dl 0
loc 192
ccs 46
cts 46
cp 1
rs 10
c 0
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getRule() 0 17 5
A getValidatorRules() 0 4 1
A addConditionalRules() 0 8 3
A isConditionalRule() 0 5 2
A clientRule() 0 11 2
A remoteRule() 0 11 1
A getAttributeName() 0 11 2
A parseNamedParameters() 0 10 1
1
<?php
2
3
namespace Proengsoft\JsValidation\Javascript;
4
5
use Proengsoft\JsValidation\JsValidatorFactory;
6
use Proengsoft\JsValidation\Support\DelegatedValidator;
7
use Proengsoft\JsValidation\Support\RuleListTrait;
8
use Proengsoft\JsValidation\Support\UseDelegatedValidatorTrait;
9
10
class RuleParser
11
{
12
    use JavascriptRulesTrait;
13
    use RuleListTrait;
14
    use UseDelegatedValidatorTrait;
15
16
    /**
17
     * Dummy Laravel validation rule for form requests.
18
     */
19
    const FORM_REQUEST_RULE_NAME = 'ProengsoftFormRequest';
20
21
    /**
22
     * Js validation rule used to validate form requests.
23
     */
24
    const FORM_REQUEST_RULE = 'laravelValidationFormRequest';
25
26
    /**
27
     * Rule used to validate remote requests.
28
     */
29
    const REMOTE_RULE = 'laravelValidationRemote';
30
31
    /**
32
     * Rule used to validate javascript fields.
33
     */
34
    const JAVASCRIPT_RULE = 'laravelValidation';
35
36
    /**
37
     * Token used to secure romte validations.
38
     *
39
     * @var null|string
40
     */
41
    protected $remoteToken;
42
43
    /**
44
     * Conditional Validations.
45 216
     *
46
     * @var array
47 216
     */
48 216
    protected $conditional = [];
49 216
50
    /**
51
     * Create a new JsValidation instance.
52
     *
53
     * @param \Proengsoft\JsValidation\Support\DelegatedValidator $validator
54
     * @param null|string $remoteToken
55
     */
56
    public function __construct(DelegatedValidator $validator, $remoteToken = null)
57
    {
58
        $this->validator = $validator;
59
        $this->remoteToken = $remoteToken;
60 72
    }
61
62 72
    /**
63 72
     * Return parsed Javascript Rule.
64
     *
65 72
     * @param string $attribute
66 36
     * @param string $rule
67 36
     * @param $parameters
68
     * @param $rawRule
69 36
     * @return array
70
     */
71
    public function getRule($attribute, $rule, $parameters, $rawRule)
72 72
    {
73
        $isConditional = $this->isConditionalRule($attribute, $rawRule);
74 72
        $isRemote = $this->isRemoteRule($rule);
75
        $isFormRequest = $this->isFormRequestRule($rule);
76
77
        if ($isFormRequest || $isConditional || $isRemote) {
78
            [$attribute, $parameters] = $this->remoteRule($attribute, $isConditional);
79
            $jsRule = $isFormRequest ? static::FORM_REQUEST_RULE : static::REMOTE_RULE;
80
        } else {
81
            [$jsRule, $attribute, $parameters] = $this->clientRule($attribute, $rule, $parameters);
0 ignored issues
show
Bug introduced by
The variable $jsRule seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
82 12
        }
83
84 12
        $attribute = $this->getAttributeName($attribute);
85
86
        return [$attribute, $jsRule, $parameters];
0 ignored issues
show
Bug introduced by
The variable $jsRule does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
87
    }
88
89
    /**
90
     * Gets rules from Validator instance.
91
     *
92
     * @return array
93
     */
94 12
    public function getValidatorRules()
95
    {
96 12
        return $this->validator->getRules();
97 12
    }
98 12
99 12
    /**
100
     * Add conditional rules.
101 12
     *
102
     * @param mixed $attribute
103
     * @param array $rules
104
     * @return void
105
     */
106
    public function addConditionalRules($attribute, $rules = [])
107
    {
108
        foreach ((array) $attribute as $key) {
109
            $current = isset($this->conditional[$key]) ? $this->conditional[$key] : [];
110 72
            $merge = head($this->validator->explodeRules((array) $rules));
111
            $this->conditional[$key] = array_merge($current, $merge);
112 72
        }
113 72
    }
114
115
    /**
116
     * Determine if rule is passed with sometimes.
117
     *
118
     * @param mixed $attribute
119
     * @param string $rule
120
     * @return bool
121
     */
122
    protected function isConditionalRule($attribute, $rule)
123
    {
124 36
        return isset($this->conditional[$attribute])
125
            && in_array($rule, $this->conditional[$attribute]);
126 36
    }
127 36
128
    /**
129 36
     * Returns Javascript parameters for remote validated rules.
130 12
     *
131
     * @param string $attribute
132
     * @param string $rule
133 36
     * @param $parameters
134
     * @return array
135
     */
136
    protected function clientRule($attribute, $rule, $parameters)
137
    {
138
        $jsRule = self::JAVASCRIPT_RULE;
139
        $method = "rule{$rule}";
140
141
        if (method_exists($this, $method)) {
142
            [$attribute, $parameters] = $this->$method($attribute, $parameters);
143 36
        }
144
145 36
        return [$jsRule, $attribute, $parameters];
146
    }
147 36
148 36
    /**
149 36
     * Returns Javascript parameters for remote validated rules.
150
     *
151
     * @param string $attribute
152 36
     * @param bool $forceRemote
153
     * @return array
154
     */
155
    protected function remoteRule($attribute, $forceRemote)
156
    {
157
        $attrHtmlName = $this->getAttributeName($attribute);
158
        $params = [
159
            $attrHtmlName,
160
            $this->remoteToken,
161 72
            $forceRemote,
162
        ];
163 72
164 72
        return [$attribute, $params];
165 24
    }
166
167
    /**
168 48
     * Handles multidimensional attribute names.
169
     *
170
     * @param mixed $attribute
171
     * @return string
172
     */
173
    protected function getAttributeName($attribute)
174
    {
175
        $attribute = str_replace(JsValidatorFactory::ASTERISK, '*', $attribute);
176
177 12
        $attributeArray = explode('.', $attribute);
178
        if (count($attributeArray) > 1) {
179
            return $attributeArray[0].'['.implode('][', array_slice($attributeArray, 1)).']';
180 12
        }
181
182 12
        return $attribute;
183
    }
184 12
185 12
    /**
186
     * Parse named parameters to $key => $value items.
187
     *
188
     * @param array $parameters
189
     * @return array
190
     */
191
    public function parseNamedParameters($parameters)
192
    {
193
        return array_reduce($parameters, function ($result, $item) {
194
            [$key, $value] = array_pad(explode('=', $item, 2), 2, null);
0 ignored issues
show
Bug introduced by
The variable $key does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $value does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
195
196
            $result[$key] = $value;
197
198
            return $result;
199
        });
200
    }
201
}
202