Completed
Push — master ( 8b132e...999aae )
by Mihail
02:25
created

ModelValidator::runValidate()   C

Complexity

Conditions 11
Paths 11

Size

Total Lines 44
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 44
rs 5.2653
cc 11
eloc 23
nc 11
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
namespace Ffcms\Core\Traits;
4
5
6
use Dflydev\DotAccessData\Data as DotData;
7
use Ffcms\Core\App;
8
use Ffcms\Core\Exception\SyntaxException;
9
use Ffcms\Core\Helper\ModelFilters;
10
use Ffcms\Core\Helper\Type\Obj;
11
use Ffcms\Core\Helper\Type\Str;
12
13
/**
14
 * Class ModelValidator. Extended realisation of model field validation
15
 * @package Ffcms\Core\Traits
16
 */
17
trait ModelValidator
18
{
19
    protected $_badAttr;
20
    protected $_sendMethod = 'POST';
21
22
    protected $_formName;
23
24
    public $_tokenRequired = false;
25
    protected $_tokenOk = true;
26
27
    /**
28
     * Initialize validator. Set csrf protection token from request data if available.
29
     * @param bool $csrf
30
     */
31
    public function initialize($csrf = false)
32
    {
33
        $this->_tokenRequired = $csrf;
34
        if ($csrf === true) {
35
            // get current token value from session
36
            $currentToken = App::$Session->get('_csrf_token', false);
37
            // set new token value to session
38
            $newToken = Str::randomLatinNumeric(mt_rand(32, 64));
39
            App::$Session->set('_csrf_token', $newToken);
40
            // if request is submited for this model - try to validate input data
41
            if ($this->send()) {
42
                // token is wrong - update bool state
43
                if ($currentToken !== $this->getRequest('_csrf_token', 'all')) {
44
                    $this->_tokenOk = false;
45
                }
46
            }
47
            // set token data to display
48
            $this->_csrf_token = $newToken;
0 ignored issues
show
Bug introduced by
The property _csrf_token does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
49
        }
50
    }
51
52
    /**
53
     * Start validation for defined fields in rules() model method.
54
     * @param array|null $rules
55
     * @return bool
56
     * @throws SyntaxException
57
     */
58
    public function runValidate(array $rules = null)
59
    {
60
        // skip validation on empty rules
61
        if ($rules === null || !Obj::isArray($rules)) {
62
            return true;
63
        }
64
65
        $success = true;
66
        // list each rule as single one
67
        foreach ($rules as $rule) {
68
            // 0 = field (property) name, 1 = filter name, 2 = filter value
69
            if ($rule[0] === null || $rule[1] === null) {
70
                continue;
71
            }
72
            $propertyName = $rule[0];
73
            $validationRule = $rule[1];
74
            $validationValue = null;
75
            if (isset($rule[2])) {
76
                $validationValue = $rule[2];
77
            }
78
79
            // check if target field defined as array and make recursive validation
80
            if (Obj::isArray($propertyName)) {
81
                $cumulateValidation = true;
82
                foreach ($propertyName as $attrNme) {
83
                    // end false condition
84
                    if (!$this->validateRecursive($attrNme, $validationRule, $validationValue)) {
85
                        $cumulateValidation = false;
86
                    }
87
                }
88
                // assign total
89
                $validate = $cumulateValidation;
90
            } else {
91
                $validate = $this->validateRecursive($propertyName, $validationRule, $validationValue);
92
            }
93
94
            // do not change condition on "true" check's (end-false-condition)
95
            if ($validate === false) {
96
                $success = false;
97
            }
98
        }
99
100
        return $success;
101
    }
102
103
    /**
104
     * Try to recursive validate field by defined rules and set result to model properties if validation is successful passed
105
     * @param string|array $propertyName
106
     * @param string $filterName
107
     * @param mixed $filterArgs
108
     * @return bool
109
     * @throws SyntaxException
110
     */
111
    public function validateRecursive($propertyName, $filterName, $filterArgs = null)
112
    {
113
        // check if we got it from form defined request method
114
        if (App::$Request->getMethod() !== $this->_sendMethod) {
115
            return false;
116
        }
117
118
        // get field value from user input data
119
        $fieldValue = $this->getFieldValue($propertyName);
0 ignored issues
show
Bug introduced by
It seems like $propertyName defined by parameter $propertyName on line 111 can also be of type array; however, Ffcms\Core\Traits\ModelValidator::getFieldValue() does only seem to accept string, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
120
121
        $check = false;
0 ignored issues
show
Unused Code introduced by
$check is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
122
        // maybe no filter required?
123
        if ($filterName === 'used') {
124
            $check = true;
125
        } elseif (Str::contains('::', $filterName)) { // sounds like a callback class::method::method
126
            // string to array via delimiter ::
127
            $callbackArray = explode('::', $filterName);
128
            // first item is a class name
129
            $class = array_shift($callbackArray);
130
            // last item its a function
131
            $method = array_pop($callbackArray);
132
            // left any items? maybe post-static callbacks?
133
            if (count($callbackArray) > 0) {
134
                foreach ($callbackArray as $obj) {
135
                    if (Str::startsWith('$', $obj) && property_exists($class, ltrim($obj, '$'))) { // sounds like a variable
136
                        $obj = ltrim($obj, '$'); // trim variable symbol '$'
137
                        $class = $class::${$obj}; // make magic :)
138
                    } elseif (method_exists($class, $obj)) { // maybe its a function?
139
                        $class = $class::$obj; // call function
140
                    } else {
141
                        throw new SyntaxException('Filter callback execution failed: ' . $filterName);
142
                    }
143
144
                }
145
            }
146
147
            // check is endpoint method exist
148
            if (method_exists($class, $method)) {
149
                $check = @$class::$method($fieldValue, $filterArgs);
150
            } else {
151
                throw new SyntaxException('Filter callback execution failed: ' . $filterName);
152
            }
153
        } elseif (method_exists('Ffcms\Core\Helper\ModelFilters', $filterName)) { // only full namespace\class path based :(
154
            if ($filterArgs != null) {
155
                $check = ModelFilters::$filterName($fieldValue, $filterArgs);
156
            } else {
157
                $check = ModelFilters::$filterName($fieldValue);
158
            }
159
        } else {
160
            throw new SyntaxException('Filter "' . $filterName . '" is not exist');
161
        }
162
        if ($check !== true) { // switch only on fail check.
163
            $this->_badAttr[] = $propertyName;
164
        } else {
165
            $field_set_name = $propertyName;
166
            // prevent array-type setting
167
            if (Str::contains('.', $field_set_name)) {
0 ignored issues
show
Bug introduced by
It seems like $field_set_name defined by $propertyName on line 165 can also be of type array; however, Ffcms\Core\Helper\Type\Str::contains() does only seem to accept string, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
168
                $field_set_name = strstr($field_set_name, '.', true);
169
            }
170
            if (property_exists($this, $field_set_name)) {
171
                if ($propertyName !== $field_set_name) { // array-based property
172
                    $dot_path = trim(strstr($propertyName, '.'), '.');
173
                    // prevent throws any exceptions for null and false objects
174
                    if (!Obj::isArray($this->{$field_set_name})) {
175
                        $this->{$field_set_name} = [];
176
                    }
177
                    // use dot-data provider to compile output array
178
                    $dotData = new DotData($this->{$field_set_name});
179
                    $dotData->set($dot_path, $fieldValue); // todo: check me!!! Here can be bug of fail parsing dots and passing path-value
180
                    // export data from dot-data lib to model property
181
                    $this->{$field_set_name} = $dotData->export();
182
                } else { // just single property
183
                    $this->{$propertyName} = $fieldValue; // refresh model property's from post data
184
                }
185
            }
186
        }
187
        return $check;
188
    }
189
190
    /**
191
     * Get field value from input POST/GET/AJAX data with defined security level (html - safe html, !secure = fully unescaped)
192
     * @param string $propertyName
193
     * @return array|null|string
194
     * @throws \InvalidArgumentException
195
     */
196
    private function getFieldValue($propertyName)
197
    {
198
        // get type of input data (where we must look it up)
199
        $inputType = Str::lowerCase($this->_sendMethod);
200
        $filterType = 'text';
201
        // get declared field sources and types
202
        $sources = $this->sources();
0 ignored issues
show
Bug introduced by
It seems like sources() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
203
        $types = $this->types();
0 ignored issues
show
Bug introduced by
It seems like types() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
204
        // validate sources for current field
205 View Code Duplication
        if (Obj::isArray($sources) && array_key_exists($propertyName, $sources)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
            $inputType = Str::lowerCase($sources[$propertyName]);
207
        }
208 View Code Duplication
        if (Obj::isArray($types)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
            // check if field is array-nested element by dots and use first element as general
210
            $filterField = $propertyName;
211
            /** @todo - i have no idea why before i use only first element of dot-nested array. Probably bug.
212
            // check if field_name is dot-separated array and use general part
213
            if (Str::contains('.', $propertyName)) {
214
                $filterField = Str::firstIn($propertyName, '.');
215
            }*/
216
            if (array_key_exists($filterField, $types)) {
217
                $filterType = Str::lowerCase($types[$filterField]);
218
            }
219
        }
220
221
        // get clear field value
222
        $propertyValue = $this->getRequest($propertyName, $inputType);
223
224
        // apply security filter for input data
225
        if ($inputType !== 'file') {
226
            if ($filterType === 'html') {
227
                $propertyValue = App::$Security->secureHtml($propertyValue);
0 ignored issues
show
Bug introduced by
It seems like $propertyValue defined by \Ffcms\Core\App::$Securi...ureHtml($propertyValue) on line 227 can also be of type null; however, Ffcms\Core\Helper\Security::secureHtml() does only seem to accept string|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
228
            } elseif ($filterType !== '!secure') {
229
                $propertyValue = App::$Security->strip_tags($propertyValue);
0 ignored issues
show
Bug introduced by
It seems like $propertyValue can also be of type null; however, Ffcms\Core\Helper\Security::strip_tags() does only seem to accept string|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
230
            }
231
        }
232
233
        return $propertyValue;
234
    }
235
236
    /**
237
     * Get fail validation attributes as array if exist
238
     * @return null|array
239
     */
240
    public function getBadAttribute()
241
    {
242
        return $this->_badAttr;
243
    }
244
245
    /**
246
     * Set model send method type. Allowed: post, get
247
     * @param string $acceptMethod
248
     */
249
    final public function setSubmitMethod($acceptMethod)
250
    {
251
        $this->_sendMethod = Str::upperCase($acceptMethod);
252
    }
253
254
    /**
255
     * Get model submit method. Allowed: post, get
256
     * @return string
257
     */
258
    final public function getSubmitMethod()
259
    {
260
        return $this->_sendMethod;
261
    }
262
263
    /**
264
     * Check if model get POST-based request as submit of SEND data
265
     * @return bool
266
     * @throws \InvalidArgumentException
267
     */
268
    final public function send()
269
    {
270
        if (!Str::equalIgnoreCase($this->_sendMethod, App::$Request->getMethod())) {
271
            return false;
272
        }
273
274
        return $this->getRequest('submit', $this->_sendMethod) !== null;
275
    }
276
277
    /**
278
     * Form default name (used in field building)
279
     * @return string
280
     */
281
    public function getFormName()
282
    {
283
        if ($this->_formName === null) {
284
            $cname = get_class($this);
285
            $this->_formName = substr($cname, strrpos($cname, '\\') + 1);
286
        }
287
288
        return $this->_formName;
289
    }
290
291
    /**
292
     * @deprecated
293
     * Get input params GET/POST/PUT method
294
     * @param string $param
295
     * @return string|null
296
     */
297
    public function getInput($param)
298
    {
299
        return $this->getRequest($param, $this->_sendMethod);
300
    }
301
302
    /**
303
     * @deprecated
304
     * Get uploaded file from user via POST request
305
     * @param string $param
306
     * @return \Symfony\Component\HttpFoundation\File\UploadedFile|null
307
     */
308
    public function getFile($param)
309
    {
310
        return $this->getRequest($param, 'file');
311
    }
312
313
    /**
314
     * Get input param for current model form based on param name and request method
315
     * @param string $param
316
     * @param string|null $method
317
     * @return string|null|array
318
     * @throws \InvalidArgumentException
319
     */
320
    public function getRequest($param, $method = null)
321
    {
322
        // build param query for http foundation request
323
        $paramQuery = $this->getFormName();
324
        if (Str::contains('.', $param)) {
325
            foreach (explode('.', $param) as $item) {
326
                $paramQuery .= '[' . $item . ']';
327
            }
328
        } else {
329
            $paramQuery .= '[' . $param . ']';
330
        }
331
332
        if ($method === null) {
333
            $method = $this->_sendMethod;
334
        }
335
336
        // get request based on method and param query
337
        $method = Str::lowerCase($method);
338
        switch ($method) {
339
            case 'get':
340
                return App::$Request->query->get($paramQuery, null, true);
341
            case 'post':
342
                return App::$Request->request->get($paramQuery, null, true);
343
            case 'file':
344
                return App::$Request->files->get($paramQuery, null, true);
345
            default:
346
                return App::$Request->get($paramQuery, null, true);
347
348
        }
349
    }
350
}