Completed
Pull Request — master (#42)
by Daniel
01:54
created

ArrayDriver::loadMetadataForClass()   C

Complexity

Conditions 7
Paths 19

Size

Total Lines 92
Code Lines 67

Duplication

Lines 24
Ratio 26.09 %

Importance

Changes 0
Metric Value
dl 24
loc 92
rs 6.4983
c 0
b 0
f 0
cc 7
eloc 67
nc 19
nop 1

How to fix   Long Method   

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
declare(strict_types=1);
4
5
namespace Psi\Component\Grid\Metadata\Driver;
6
7
use Metadata\Driver\AdvancedDriverInterface;
8
use Psi\Component\Grid\Metadata\ActionMetadata;
9
use Psi\Component\Grid\Metadata\ClassMetadata;
10
use Psi\Component\Grid\Metadata\ColumnMetadata;
11
use Psi\Component\Grid\Metadata\FilterMetadata;
12
use Psi\Component\Grid\Metadata\GridMetadata;
13
use Psi\Component\Grid\Metadata\QueryMetadata;
14
15
class ArrayDriver implements AdvancedDriverInterface
16
{
17
    /**
18
     * @var array
19
     */
20
    private $config;
21
22
    /**
23
     * @param array $config
24
     */
25
    public function __construct(array $config)
26
    {
27
        $this->config = $config;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function loadMetadataForClass(\ReflectionClass $class)
34
    {
35
        if (!isset($this->config[$class->getName()])) {
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
36
            return;
37
        }
38
39
        $config = $this->resolveConfig([
40
            'grids' => [],
41
            'queries' => [],
42
        ], $this->config[$class->getName()]);
0 ignored issues
show
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
43
44
        $queries = [];
45
        foreach ($config['queries'] as $queryName => $queryConfig) {
46
            $queryConfig = $this->resolveConfig([
47
                'name' => null,
48
                'selects' => [],
49
                'joins' => [],
50
                'criteria' => [],
51
            ], $queryConfig);
52
            $queries[$queryName] = new QueryMetadata(
53
                $queryName, $queryConfig['selects'], $queryConfig['joins'], $queryConfig['criteria']
54
            );
55
        }
56
57
        foreach ($config['grids'] as $gridName => $gridConfig) {
58
            $gridConfig = $this->resolveConfig([
59
                'name' => null,
60
                'query' => null,
61
                'columns' => [],
62
                'filters' => [],
63
                'actions' => [],
64
                'page_size' => 50,
65
            ], $gridConfig);
66
67
            $columns = [];
68 View Code Duplication
            foreach ($gridConfig['columns'] as $columnName => $columnConfig) {
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...
69
                $columnConfig = $this->resolveConfig([
70
                    'type' => null,
71
                    'options' => [],
72
                ], $columnConfig);
73
74
                $columns[$columnName] = new ColumnMetadata(
75
                    $columnName,
76
                    $columnConfig['type'],
77
                    $columnConfig['options']
78
                );
79
            }
80
81
            $filters = [];
82
            foreach ($gridConfig['filters'] as $filterName => $filterConfig) {
83
                $filterConfig = $this->resolveConfig([
84
                    'type' => null,
85
                    'field' => null,
86
                    'options' => [],
87
                ], $filterConfig);
88
89
                $filters[$filterName] = new FilterMetadata(
90
                    $filterName,
91
                    $filterConfig['type'],
92
                    $filterConfig['field'],
93
                    $filterConfig['options']
94
                );
95
            }
96
97
            $actions = [];
98 View Code Duplication
            foreach ($gridConfig['actions'] as $actionName => $actionConfig) {
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...
99
                $actionConfig = $this->resolveConfig([
100
                    'type' => null,
101
                    'options' => [],
102
                ], $actionConfig);
103
104
                $actions[$actionName] = new ActionMetadata(
105
                    $actionName,
106
                    $actionConfig['type'],
107
                    $actionConfig['options']
108
                );
109
            }
110
111
            $grids[$gridName] = new GridMetadata(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$grids was never initialized. Although not strictly required by PHP, it is generally a good practice to add $grids = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
112
                $gridName,
113
                $columns,
114
                $filters,
115
                $actions,
116
                $gridConfig['page_size'],
117
                $gridConfig['query']
118
            );
119
        }
120
121
        $classMetadata = new ClassMetadata($class->getName(), $grids, $queries);
0 ignored issues
show
Bug introduced by
The variable $grids does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
Consider using $class->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
122
123
        return $classMetadata;
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function getAllClassNames()
130
    {
131
        return array_keys($this->config);
132
    }
133
134
    private function resolveConfig(array $defaultConfig, array $config)
135
    {
136 View Code Duplication
        if ($diff = array_diff(array_keys($config), array_keys($defaultConfig))) {
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...
137
            throw new \InvalidArgumentException(sprintf(
138
                'Invalid configuration keys "%s" for grid, valid keys: "%s"',
139
                implode('", "', $diff), implode('", "', array_keys($defaultConfig))
140
            ));
141
        }
142
143
        return array_merge($defaultConfig, $config);
144
    }
145
}
146