Completed
Push — master ( d040ca...24a963 )
by Mihail
06:36
created

ModelValidator::getFieldValue()   D

Complexity

Conditions 10
Paths 64

Size

Total Lines 36
Code Lines 20

Duplication

Lines 6
Ratio 16.67 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 6
loc 36
rs 4.8196
cc 10
eloc 20
nc 64
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 Ffcms\Core\App;
7
use Ffcms\Core\Exception\SyntaxException;
8
use Ffcms\Core\Filter\Native;
9
use Ffcms\Core\Helper\Type\Obj;
10
use Ffcms\Core\Helper\Type\Str;
11
use Dflydev\DotAccessData\Data as DotData;
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
73
            // check if target field defined as array and make recursive validation
74
            if (Obj::isArray($rule[0])) {
75
                $validate_foreach = true;
76
                foreach ($rule[0] as $field_name) {
77
                    // end false condition
78
                    if (!$this->validateRecursive($field_name, $rule[1], $rule[2])) {
79
                        $validate_foreach = false;
80
                    }
81
                }
82
                // assign total
83
                $validate = $validate_foreach;
84
            } else {
85
                $validate = $this->validateRecursive($rule[0], $rule[1], $rule[2]);
86
            }
87
88
            // do not change condition on "true" check's (end-false-condition)
89
            if ($validate === false) {
90
                $success = false;
91
            }
92
        }
93
94
        return $success;
95
    }
96
97
    /**
98
     * Try to recursive validate field by defined rules and set result to model properties if validation is successful passed
99
     * @param string|array $field_name
100
     * @param string $filter_name
101
     * @param mixed $filter_argv
102
     * @return bool
103
     * @throws SyntaxException
104
     */
105
    public function validateRecursive($field_name, $filter_name, $filter_argv = null)
106
    {
107
        // check if we got it from form defined request method
108
        if (App::$Request->getMethod() !== $this->_sendMethod) {
109
            return false;
110
        }
111
112
        // get field value from user input data
113
        $field_value = $this->getFieldValue($field_name);
0 ignored issues
show
Bug introduced by
It seems like $field_name defined by parameter $field_name on line 105 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...
114
115
        $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...
116
        // maybe no filter required?
117
        if ($filter_name === 'used') {
118
            $check = true;
119
        } elseif (Str::contains('::', $filter_name)) { // sounds like a callback class::method::method
120
            // string to array via delimiter ::
121
            $callbackArray = explode('::', $filter_name);
122
            // first item is a class name
123
            $class = array_shift($callbackArray);
124
            // last item its a function
125
            $method = array_pop($callbackArray);
126
            // left any items? maybe post-static callbacks?
127
            if (count($callbackArray) > 0) {
128
                foreach ($callbackArray as $obj) {
129
                    if (Str::startsWith('$', $obj) && property_exists($class, ltrim($obj, '$'))) { // sounds like a variable
130
                        $obj = ltrim($obj, '$'); // trim variable symbol '$'
131
                        $class = $class::$$obj; // make magic :)
132
                    } elseif (method_exists($class, $obj)) { // maybe its a function?
133
                        $class = $class::$obj; // call function
134
                    } else {
135
                        throw new SyntaxException('Filter callback execution failed: ' . $filter_name);
136
                    }
137
138
                }
139
            }
140
141
            // check is endpoint method exist
142
            if (method_exists($class, $method)) {
143
                $check = @$class::$method($field_value, $filter_argv);
144
            } else {
145
                throw new SyntaxException('Filter callback execution failed: ' . $filter_name);
146
            }
147
        } elseif (method_exists('Ffcms\Core\Filter\Native', $filter_name)) { // only full namespace\class path based :(
148
            if ($filter_argv != null) {
149
                $check = Native::$filter_name($field_value, $filter_argv);
150
            } else {
151
                $check = Native::$filter_name($field_value);
152
            }
153
        } else {
154
            throw new SyntaxException('Filter "' . $filter_name . '" is not exist');
155
        }
156
        if ($check !== true) { // switch only on fail check.
157
            $this->_badAttr[] = $field_name;
158
        } else {
159
            $field_set_name = $field_name;
160
            // prevent array-type setting
161
            if (Str::contains('.', $field_set_name)) {
162
                $field_set_name = strstr($field_set_name, '.', true);
163
            }
164
            if (property_exists($this, $field_set_name)) {
165
                if ($field_name !== $field_set_name) { // array-based property
166
                    $dot_path = trim(strstr($field_name, '.'), '.');
167
                    // prevent throws any exceptions for null and false objects
168
                    if (!Obj::isArray($this->{$field_set_name})) {
169
                        $this->{$field_set_name} = [];
170
                    }
171
                    // use dot-data provider to compile output array
172
                    $dotData = new DotData($this->{$field_set_name});
173
                    $dotData->set($dot_path, $field_value); // todo: check me!!! Here can be bug of fail parsing dots and passing path-value
174
                    // export data from dot-data lib to model property
175
                    $this->{$field_set_name} = $dotData->export();
176
                } else { // just single property
177
                    $this->{$field_name} = $field_value; // refresh model property's from post data
178
                }
179
            }
180
        }
181
        return $check;
182
    }
183
184
    /**
185
     * Get field value from input POST/GET/AJAX data with defined security level (html - safe html, !secure = fully unescaped)
186
     * @param string $field_name
187
     * @return array|null|string
188
     * @throws \InvalidArgumentException
189
     */
190
    private function getFieldValue($field_name)
191
    {
192
        // get type of input data (where we must look it up)
193
        $sources = [];
194
        $types = [];
195
        $inputType = Str::lowerCase($this->_sendMethod);
196
        $filterType = 'text';
197
        // check input data type. Maybe file or input (text)
198
        if (method_exists($this, 'sources')) {
199
            $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...
200
        }
201
        if (method_exists($this, 'types')) {
202
            $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...
203
        }
204
        // validate sources for current field
205 View Code Duplication
        if (Obj::isArray($sources) && array_key_exists($field_name, $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[$field_name]);
207
        }
208 View Code Duplication
        if (Obj::isArray($types) && array_key_exists($field_name, $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
            $filterType = Str::lowerCase($types[$field_name]);
210
        }
211
212
        // get clear field value
213
        $field_value = $this->getRequest($field_name, $inputType);
214
215
        // apply security filter for input data
216
        if ($inputType !== 'file') {
217
            if ($filterType === 'html') {
218
                $field_value = App::$Security->secureHtml($field_value);
0 ignored issues
show
Bug introduced by
It seems like $field_value defined by \Ffcms\Core\App::$Securi...ecureHtml($field_value) on line 218 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...
219
            } elseif ($filterType !== '!secure') {
220
                $field_value = App::$Security->strip_tags($field_value);
0 ignored issues
show
Bug introduced by
It seems like $field_value 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...
221
            }
222
        }
223
224
        return $field_value;
225
    }
226
227
    /**
228
     * Get fail validation attributes as array if exist
229
     * @return null|array
230
     */
231
    public function getBadAttribute()
232
    {
233
        return $this->_badAttr;
234
    }
235
236
    /**
237
     * Set model send method type. Allowed: post, get
238
     * @param string $acceptMethod
239
     */
240
    final public function setSubmitMethod($acceptMethod)
241
    {
242
        $this->_sendMethod = Str::upperCase($acceptMethod);
243
    }
244
245
    /**
246
     * Get model submit method. Allowed: post, get
247
     * @return string
248
     */
249
    final public function getSubmitMethod()
250
    {
251
        return $this->_sendMethod;
252
    }
253
254
    /**
255
     * Check if model get POST-based request as submit of SEND data
256
     * @return bool
257
     * @throws \InvalidArgumentException
258
     */
259
    final public function send()
260
    {
261
        if (!Str::equalIgnoreCase($this->_sendMethod, App::$Request->getMethod())) {
262
            return false;
263
        }
264
265
        return $this->getRequest('submit', $this->_sendMethod) !== null;
266
    }
267
268
    /**
269
     * Form default name (used in field building)
270
     * @return string
271
     */
272
    public function getFormName()
273
    {
274
        if ($this->_formName === null) {
275
            $cname = get_class($this);
276
            $this->_formName = substr($cname, strrpos($cname, '\\') + 1);
277
        }
278
279
        return $this->_formName;
280
    }
281
282
    /**
283
     * @deprecated
284
     * Get input params GET/POST/PUT method
285
     * @param string $param
286
     * @return string|null
287
     */
288
    public function getInput($param)
289
    {
290
        return $this->getRequest($param, $this->_sendMethod);
291
    }
292
293
    /**
294
     * @deprecated
295
     * Get uploaded file from user via POST request
296
     * @param string $param
297
     * @return \Symfony\Component\HttpFoundation\File\UploadedFile|null
298
     */
299
    public function getFile($param)
300
    {
301
        return $this->getRequest($param, 'file');
302
    }
303
304
    /**
305
     * Get input param for current model form based on param name and request method
306
     * @param string $param
307
     * @param string|null $method
308
     * @return string|null|array
309
     * @throws \InvalidArgumentException
310
     */
311
    public function getRequest($param, $method = null)
312
    {
313
        // build param query for http foundation request
314
        $paramQuery = $this->getFormName();
315
        if (Str::contains('.', $param)) {
316
            foreach (explode('.', $param) as $item) {
317
                $paramQuery .= '[' . $item . ']';
318
            }
319
        } else {
320
            $paramQuery .= '[' . $param . ']';
321
        }
322
323
        if ($method === null) {
324
            $method = $this->_sendMethod;
325
        }
326
327
        // get request based on method and param query
328
        $method = Str::lowerCase($method);
329
        switch ($method) {
330
            case 'get':
331
                return App::$Request->query->get($paramQuery, null, true);
332
            case 'post':
333
                return App::$Request->request->get($paramQuery, null, true);
334
            case 'file':
335
                return App::$Request->files->get($paramQuery, null, true);
336
            default:
337
                return App::$Request->get($paramQuery, null, true);
338
339
        }
340
    }
341
}