ModelValidator   C
last analyzed

Complexity

Total Complexity 54

Size/Duplication

Total Lines 328
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 136
c 3
b 0
f 0
dl 0
loc 328
rs 6.4799
wmc 54

11 Methods

Rating   Name   Duplication   Size   Complexity  
A getBadAttributes() 0 3 1
A setSubmitMethod() 0 3 1
A getFile() 0 3 1
A send() 0 7 2
A getSubmitMethod() 0 3 1
A initialize() 0 18 4
A getFieldValue() 0 33 6
B getRequest() 0 39 9
D validateRecursive() 0 82 18
A getInput() 0 3 1
B runValidate() 0 44 10

How to fix   Complexity   

Complex Class

Complex classes like ModelValidator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ModelValidator, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Ffcms\Core\Traits;
4
5
use Dflydev\DotAccessData\Data as DotData;
6
use Ffcms\Core\App;
7
use Ffcms\Core\Exception\SyntaxException;
8
use Ffcms\Core\Helper\Crypt;
9
use Ffcms\Core\Helper\ModelFilters;
10
use Ffcms\Core\Helper\Type\Any;
11
use Ffcms\Core\Helper\Type\Obj;
12
use Ffcms\Core\Helper\Type\Str;
13
14
/**
15
 * Class ModelValidator. Extended realisation of model field validation
16
 * @package Ffcms\Core\Traits
17
 */
18
trait ModelValidator
19
{
20
    protected $_badAttr;
21
    protected $_sendMethod = 'POST';
22
23
    protected $_formName;
24
25
    public $_tokenRequired = false;
26
    protected $_tokenOk = true;
27
28
    /**
29
     * Initialize validator. Set csrf protection token from request data if available.
30
     * @param bool $csrf
31
     */
32
    public function initialize($csrf = false)
33
    {
34
        $this->_tokenRequired = $csrf;
35
        if ($csrf) {
36
            // get current token value from session
37
            $currentToken = App::$Session->get('_csrf_token', false);
38
            // set new token value to session
39
            $newToken = Crypt::randomString(mt_rand(32, 64));
40
            App::$Session->set('_csrf_token', $newToken);
41
            // if request is submited for this model - try to validate input data
42
            if ($this->send()) {
43
                // token is wrong - update bool state
44
                if ($currentToken !== $this->getRequest('_csrf_token')) {
45
                    $this->_tokenOk = false;
46
                }
47
            }
48
            // set token data to display
49
            $this->_csrf_token = $newToken;
0 ignored issues
show
Bug Best Practice introduced by
The property _csrf_token does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
50
        }
51
    }
52
53
    /**
54
     * Start validation for defined fields in rules() model method.
55
     * @param array|null $rules
56
     * @return bool
57
     * @throws SyntaxException
58
     */
59
    public function runValidate(array $rules = null)
60
    {
61
        // skip validation on empty rules
62
        if ($rules === null) {
63
            return true;
64
        }
65
66
        $success = true;
67
        // list each rule as single one
68
        foreach ($rules as $rule) {
69
            // 0 = field (property) name, 1 = filter name, 2 = filter value
70
            if ($rule[0] === null || $rule[1] === null) {
71
                continue;
72
            }
73
74
            $propertyName = $rule[0];
75
            $validationRule = $rule[1];
76
            $validationValue = null;
77
            if (isset($rule[2])) {
78
                $validationValue = $rule[2];
79
            }
80
81
            // check if target field defined as array and make recursive validation
82
            if (Any::isArray($propertyName)) {
83
                $cumulateValidation = true;
84
                foreach ($propertyName as $attrNme) {
85
                    // end false condition
86
                    if (!$this->validateRecursive($attrNme, $validationRule, $validationValue)) {
87
                        $cumulateValidation = false;
88
                    }
89
                }
90
                // assign total
91
                $validate = $cumulateValidation;
92
            } else {
93
                $validate = $this->validateRecursive($propertyName, $validationRule, $validationValue);
94
            }
95
96
            // do not change condition on "true" check's (end-false-condition)
97
            if ($validate === false) {
98
                $success = false;
99
            }
100
        }
101
102
        return $success;
103
    }
104
105
    /**
106
     * Try to recursive validate field by defined rules and set result to model properties if validation is successful passed
107
     * @param string|array $propertyName
108
     * @param string $filterName
109
     * @param mixed $filterArgs
110
     * @return bool
111
     * @throws SyntaxException
112
     */
113
    public function validateRecursive($propertyName, $filterName, $filterArgs = null)
114
    {
115
        // check if we got it from form defined request method
116
        if (App::$Request->getMethod() !== $this->_sendMethod) {
117
            return false;
118
        }
119
120
        // get field value from user input data
121
        $fieldValue = $this->getFieldValue($propertyName);
0 ignored issues
show
Bug introduced by
It seems like $propertyName can also be of type array; however, parameter $propertyName of Ffcms\Core\Traits\ModelValidator::getFieldValue() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

121
        $fieldValue = $this->getFieldValue(/** @scrutinizer ignore-type */ $propertyName);
Loading history...
122
123
        $check = false;
124
        // maybe no filter required?
125
        if ($filterName === 'used') {
126
            $check = true;
127
        } elseif (Str::contains('::', $filterName)) { // sounds like a callback class::method::method
128
            // string to array via delimiter ::
129
            $callbackArray = explode('::', $filterName);
130
            // first item is a class name
131
            $class = array_shift($callbackArray);
132
            // last item its a function
133
            $method = array_pop($callbackArray);
134
            // left any items? maybe post-static callbacks?
135
            if (count($callbackArray) > 0) {
136
                foreach ($callbackArray as $obj) {
137
                    if (Str::startsWith('$', $obj) && property_exists($class, ltrim($obj, '$'))) { // sounds like a variable
138
                        $obj = ltrim($obj, '$'); // trim variable symbol '$'
139
                        $class = $class::${$obj}; // make magic :)
140
                    } elseif (method_exists($class, $obj)) { // maybe its a function?
141
                        $class = $class::$obj; // call function
142
                    } else {
143
                        throw new SyntaxException('Filter callback execution failed: ' . $filterName);
144
                    }
145
                }
146
            }
147
148
            // check is endpoint method exist
149
            if (method_exists($class, $method)) {
150
                $check = @$class::$method($fieldValue, $filterArgs);
151
            } else {
152
                throw new SyntaxException('Filter callback execution failed: ' . $filterName);
153
            }
154
        } elseif (method_exists('Ffcms\Core\Helper\ModelFilters', $filterName)) { // only full namespace\class path based :(
155
            if ($filterArgs != null) {
156
                $check = ModelFilters::$filterName($fieldValue, $filterArgs);
157
            } else {
158
                $check = ModelFilters::$filterName($fieldValue);
159
            }
160
        } else {
161
            throw new SyntaxException('Filter "' . $filterName . '" is not exist');
162
        }
163
164
        // if one from all validation tests is fail - mark as incorrect attribute
165
        if ($check !== true) {
166
            $this->_badAttr[] = $propertyName;
167
            if (App::$Debug) {
168
                App::$Debug->addMessage('Validation failed. Property: ' . $propertyName . ', filter: ' . $filterName, 'warning');
0 ignored issues
show
Bug introduced by
Are you sure $propertyName of type array|string can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

168
                App::$Debug->addMessage('Validation failed. Property: ' . /** @scrutinizer ignore-type */ $propertyName . ', filter: ' . $filterName, 'warning');
Loading history...
169
            }
170
        } else {
171
            $field_set_name = $propertyName;
172
            // prevent array-type setting
173
            if (Str::contains('.', $field_set_name)) {
0 ignored issues
show
Bug introduced by
It seems like $field_set_name can also be of type array; however, parameter $where of Ffcms\Core\Helper\Type\Str::contains() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

173
            if (Str::contains('.', /** @scrutinizer ignore-type */ $field_set_name)) {
Loading history...
174
                $field_set_name = strstr($field_set_name, '.', true);
0 ignored issues
show
Bug introduced by
It seems like $field_set_name can also be of type array; however, parameter $haystack of strstr() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

174
                $field_set_name = strstr(/** @scrutinizer ignore-type */ $field_set_name, '.', true);
Loading history...
175
            }
176
            if (property_exists($this, $field_set_name)) {
0 ignored issues
show
Bug introduced by
It seems like $field_set_name can also be of type array; however, parameter $property of property_exists() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

176
            if (property_exists($this, /** @scrutinizer ignore-type */ $field_set_name)) {
Loading history...
177
                if ($propertyName !== $field_set_name) { // array-based property
178
                    $dot_path = trim(strstr($propertyName, '.'), '.');
179
                    // prevent throws any exceptions for null and false objects
180
                    if (!Any::isArray($this->{$field_set_name})) {
181
                        $this->{$field_set_name} = [];
182
                    }
183
184
                    // use dot-data provider to compile output array
185
                    $dotData = new DotData($this->{$field_set_name});
186
                    $dotData->set($dot_path, $fieldValue); // todo: check me!!! Here can be bug of fail parsing dots and passing path-value
187
                    // export data from dot-data lib to model property
188
                    $this->{$field_set_name} = $dotData->export();
189
                } else { // just single property
190
                    $this->{$propertyName} = $fieldValue; // refresh model property's from post data
191
                }
192
            }
193
        }
194
        return $check;
195
    }
196
197
    /**
198
     * Get field value from input POST/GET/AJAX data with defined security level (html - safe html, !secure = fully unescaped)
199
     * @param string $propertyName
200
     * @return array|null|string
201
     * @throws \InvalidArgumentException
202
     */
203
    private function getFieldValue($propertyName)
204
    {
205
        // get type of input data (where we must look it up)
206
        $inputType = Str::lowerCase($this->_sendMethod);
207
        $filterType = 'text';
208
        // get declared field sources and types
209
        $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? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

209
        /** @scrutinizer ignore-call */ 
210
        $sources = $this->sources();
Loading history...
210
        $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? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

210
        /** @scrutinizer ignore-call */ 
211
        $types = $this->types();
Loading history...
211
        // validate sources for current field
212
        if (array_key_exists($propertyName, $sources)) {
213
            $inputType = Str::lowerCase($sources[$propertyName]);
214
        }
215
216
217
        // check if field is array-nested element by dots and use first element as general
218
        $filterField = $propertyName;
219
        if (array_key_exists($filterField, $types)) {
220
            $filterType = Str::lowerCase($types[$filterField]);
221
        }
222
223
        // get clear field value
224
        $propertyValue = $this->getRequest($propertyName, $inputType);
225
226
        // apply security filter for input data
227
        if ($inputType !== 'file') {
228
            if ($filterType === 'html') {
229
                $propertyValue = App::$Security->secureHtml($propertyValue);
230
            } elseif ($filterType !== '!secure') {
231
                $propertyValue = App::$Security->strip_tags($propertyValue);
232
            }
233
        }
234
235
        return $propertyValue;
236
    }
237
238
    /**
239
     * Get fail validation attributes as array if exist
240
     * @return null|array
241
     */
242
    public function getBadAttributes(): ?array
243
    {
244
        return $this->_badAttr;
245
    }
246
247
    /**
248
     * Set model send method type. Allowed: post, get
249
     * @param string $acceptMethod
250
     */
251
    final public function setSubmitMethod($acceptMethod): void
252
    {
253
        $this->_sendMethod = Str::upperCase($acceptMethod);
254
    }
255
256
    /**
257
     * Get model submit method. Allowed: post, get
258
     * @return string
259
     */
260
    final public function getSubmitMethod(): ?string
261
    {
262
        return $this->_sendMethod;
263
    }
264
265
    /**
266
     * Check if model get POST-based request as submit of SEND data
267
     * @return bool
268
     * @throws \InvalidArgumentException
269
     */
270
    final public function send()
271
    {
272
        if (!Str::equalIgnoreCase($this->_sendMethod, App::$Request->getMethod())) {
273
            return false;
274
        }
275
276
        return $this->getRequest('submit', $this->_sendMethod) !== null;
277
    }
278
279
    /**
280
     * @deprecated
281
     * Get input params GET/POST/PUT method
282
     * @param string $param
283
     * @return string|null
284
     */
285
    public function getInput($param)
286
    {
287
        return $this->getRequest($param, $this->_sendMethod);
288
    }
289
290
    /**
291
     * @deprecated
292
     * Get uploaded file from user via POST request
293
     * @param string $param
294
     * @return \Symfony\Component\HttpFoundation\File\UploadedFile|null
295
     */
296
    public function getFile($param)
297
    {
298
        return $this->getRequest($param, 'file');
299
    }
300
301
    /**
302
     * Get input value based on param path and request method
303
     * @param string $param
304
     * @param string|null $method
305
     * @return mixed
306
     */
307
    public function getRequest($param, $method = null)
308
    {
309
        if ($method === null) {
310
            $method = $this->_sendMethod;
311
        }
312
313
        $method = Str::lowerCase($method);
314
        // get root request as array or string
315
        switch ($method) {
316
            case 'get':
317
                $request = App::$Request->query->get($this->getFormName(), null);
0 ignored issues
show
Bug introduced by
It seems like getFormName() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

317
                $request = App::$Request->query->get($this->/** @scrutinizer ignore-call */ getFormName(), null);
Loading history...
318
                break;
319
            case 'post':
320
                $request = App::$Request->request->get($this->getFormName(), null);
321
                break;
322
            case 'file':
323
                $request = App::$Request->files->get($this->getFormName(), null);
324
                break;
325
            default:
326
                $request = App::$Request->get($this->getFormName(), null);
327
                break;
328
        }
329
330
        $response = null;
331
        // param is a dot-separated array type
332
        if (Str::contains('.', $param)) {
333
            $response = $request;
334
            foreach (explode('.', $param) as $path) {
335
                if ($response !== null && !array_key_exists($path, $response)) {
336
                    return null;
337
                }
338
                // find deep array nesting offset
339
                $response = $response[$path];
340
            }
341
        } else {
342
            $response = $request[$param];
343
        }
344
345
        return $response;
346
    }
347
}
348