Completed
Push — master ( a02648...5816bc )
by Ryan
11:09
created

NullableGuesser::guess()   D

Complexity

Conditions 9
Paths 11

Size

Total Lines 32
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 9
eloc 13
c 3
b 0
f 0
nc 11
nop 1
dl 0
loc 32
rs 4.909
1
<?php namespace Anomaly\Streams\Platform\Ui\Form\Component\Field\Guesser;
2
3
use Anomaly\Streams\Platform\Entry\Contract\EntryInterface;
4
use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
5
6
class NullableGuesser
7
{
8
9
    /**
10
     * Guess the nullable rule.
11
     *
12
     * @param FormBuilder $builder
13
     */
14
    public function guess(FormBuilder $builder)
15
    {
16
        $fields = $builder->getFields();
17
18
        foreach ($fields as &$field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
19
20
            // Skip if nullable
21
            if (isset($field['rules']) && in_array('nullable', $field['rules'])) {
22
                continue;
23
            }
24
25
            // If the field depends on other fields, we not add nullable here
26
            // because validation will not be performed at all on this field
27
            if (! empty($field['rules'])) {
28
                if (preg_grep("/required_.*/", $field['rules'])) {
29
                    continue;
30
                }
31
            }
32
33
            // If not required then nullable.
34
            if (isset($field['required']) && $field['required'] == false) {
35
                $field['rules'][] = 'nullable';
36
            }
37
38
            // If not specified then it's nullable
39
            if (!isset($field['required'])) {
40
                $field['rules'][] = 'nullable';
41
            }
42
        }
43
44
        $builder->setFields($fields);
45
    }
46
}
47