Passed
Push — master ( af2f54...359aba )
by Mihail
03:15
created

ModelValidator   C

Complexity

Total Complexity 54

Size/Duplication

Total Lines 328
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 328
rs 6.8539
c 0
b 0
f 0
wmc 54

11 Methods

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

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\ModelFilters;
9
use Ffcms\Core\Helper\Type\Any;
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')) {
44
                    $this->_tokenOk = false;
45
                }
46
            }
47
            // set token data to display
48
            $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...
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) {
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
73
            $propertyName = $rule[0];
74
            $validationRule = $rule[1];
75
            $validationValue = null;
76
            if (isset($rule[2])) {
77
                $validationValue = $rule[2];
78
            }
79
80
            // check if target field defined as array and make recursive validation
81
            if (Any::isArray($propertyName)) {
82
                $cumulateValidation = true;
83
                foreach ($propertyName as $attrNme) {
84
                    // end false condition
85
                    if (!$this->validateRecursive($attrNme, $validationRule, $validationValue)) {
86
                        $cumulateValidation = false;
87
                    }
88
                }
89
                // assign total
90
                $validate = $cumulateValidation;
91
            } else {
92
                $validate = $this->validateRecursive($propertyName, $validationRule, $validationValue);
93
            }
94
95
            // do not change condition on "true" check's (end-false-condition)
96
            if ($validate === false) {
97
                $success = false;
98
            }
99
        }
100
101
        return $success;
102
    }
103
104
    /**
105
     * Try to recursive validate field by defined rules and set result to model properties if validation is successful passed
106
     * @param string|array $propertyName
107
     * @param string $filterName
108
     * @param mixed $filterArgs
109
     * @return bool
110
     * @throws SyntaxException
111
     */
112
    public function validateRecursive($propertyName, $filterName, $filterArgs = null)
113
    {
114
        // check if we got it from form defined request method
115
        if (App::$Request->getMethod() !== $this->_sendMethod) {
116
            return false;
117
        }
118
119
        // get field value from user input data
120
        $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

120
        $fieldValue = $this->getFieldValue(/** @scrutinizer ignore-type */ $propertyName);
Loading history...
121
122
        $check = false;
123
        // maybe no filter required?
124
        if ($filterName === 'used') {
125
            $check = true;
126
        } elseif (Str::contains('::', $filterName)) { // sounds like a callback class::method::method
127
            // string to array via delimiter ::
128
            $callbackArray = explode('::', $filterName);
129
            // first item is a class name
130
            $class = array_shift($callbackArray);
131
            // last item its a function
132
            $method = array_pop($callbackArray);
133
            // left any items? maybe post-static callbacks?
134
            if (count($callbackArray) > 0) {
135
                foreach ($callbackArray as $obj) {
136
                    if (Str::startsWith('$', $obj) && property_exists($class, ltrim($obj, '$'))) { // sounds like a variable
137
                        $obj = ltrim($obj, '$'); // trim variable symbol '$'
138
                        $class = $class::${$obj}; // make magic :)
139
                    } elseif (method_exists($class, $obj)) { // maybe its a function?
140
                        $class = $class::$obj; // call function
141
                    } else {
142
                        throw new SyntaxException('Filter callback execution failed: ' . $filterName);
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
163
        // if one from all validation tests is fail - mark as incorrect attribute
164
        if ($check !== true) {
165
            $this->_badAttr[] = $propertyName;
166
            if (App::$Debug) {
167
                App::$Debug->addMessage('Validation failed. Property: ' . $propertyName . ', filter: ' . $filterName, 'warning');
0 ignored issues
show
Bug introduced by
Are you sure $propertyName of type string|array 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

167
                App::$Debug->addMessage('Validation failed. Property: ' . /** @scrutinizer ignore-type */ $propertyName . ', filter: ' . $filterName, 'warning');
Loading history...
168
            }
169
        } else {
170
            $field_set_name = $propertyName;
171
            // prevent array-type setting
172
            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

172
            if (Str::contains('.', /** @scrutinizer ignore-type */ $field_set_name)) {
Loading history...
173
                $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

173
                $field_set_name = strstr(/** @scrutinizer ignore-type */ $field_set_name, '.', true);
Loading history...
174
            }
175
            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

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

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

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

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