Completed
Push — master ( d015d4...c50906 )
by Mikołaj
02:42
created

Navigation::create()   C

Complexity

Conditions 11
Paths 43

Size

Total Lines 126
Code Lines 59

Duplication

Lines 19
Ratio 15.08 %

Importance

Changes 0
Metric Value
cc 11
eloc 59
c 0
b 0
f 0
nc 43
nop 0
dl 19
loc 126
rs 5.2653

How to fix   Long Method    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 Rudolf\Modules\Appearance\Menu;
4
5
use Rudolf\Component\Helpers\Navigation\MenuItem;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Rudolf\Modules\Appearance\Menu\MenuItem.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
6
use Rudolf\Component\Helpers\Navigation\MenuItemCollection;
7
8
class Navigation
9
{
10
    /**
11
     * @var int
12
     */
13
    private $rootID = 0;
14
15
    /**
16
     * @var string
17
     */
18
    private $type;
19
20
    /**
21
     * @var MenuItemCollection
22
     */
23
    private $menuItemsCollection;
24
    /**
25
     * @var int
26
     */
27
    private $nesting;
28
29
    /**
30
     * Set root ID.
31
     *
32
     * @param int $id ID of element to start create tree. Set 0 to create full tree
33
     */
34
    public function setRootID($id)
35
    {
36
        $this->rootID = (int) $id;
37
    }
38
39
    /**
40
     * @return int
41
     */
42
    public function getRootID()
43
    {
44
        return $this->rootID;
45
    }
46
47
    /**
48
     * Menu type defined in menu_types table.
49
     *
50
     * @param string $type
51
     */
52
    public function setType($type)
53
    {
54
        $this->type = $type;
55
    }
56
57
    /**
58
     * @return string
59
     */
60
    public function getType()
61
    {
62
        return $this->type;
63
    }
64
65
    /**
66
     * Set items.
67
     *
68
     * @param MenuItemCollection $items
69
     */
70
    public function setItems(MenuItemCollection $items)
71
    {
72
        $this->menuItemsCollection = $items;
73
    }
74
75
    /**
76
     * @return array
77
     */
78
    public function getItems()
79
    {
80
        return $this->menuItemsCollection->getByType($this->getType());
81
    }
82
83
    /**
84
     * Set generated menu code nesting.
85
     *
86
     * @param int $nesting
87
     */
88
    public function setNesting($nesting)
89
    {
90
        $this->nesting = $nesting;
91
    }
92
93
    /**
94
     * @return mixed
95
     */
96
    public function getNesting()
97
    {
98
        return $this->nesting;
99
    }
100
101
    /**
102
     * Put value is not empty.
103
     *
104
     * @param string       $attribute
105
     * @param string|array $value
106
     *
107
     * @return string
108
     */
109 View Code Duplication
    private function isAttribute($attribute, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
110
    {
111
        if (is_array($value)) {
112
            array_filter($value);
113
            $value = trim(implode(' ', $value));
114
115
            return !empty($value) ? ' '.$attribute.'="'.$value.'"' : '';
116
        }
117
118
        return (isset($value) and !empty($value)) ? ' '.$attribute.'="'.trim($value).'"' : '';
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as and instead of && is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
119
    }
120
121
122
    /**
123
     * Menu creator.
124
     *
125
     * @link http://pastebin.com/GAFvSew4
126
     *
127
     * @author J. Bruni - original author
128
     *
129
     * @return string|bool
130
     */
131
    public function create()
132
    {
133
        $root_id = $this->getRootID();
134
        $items = $this->getItems();
135
        $nesting = $this->getNesting();
136
137
        if (empty($items)) {
138
            return false;
139
        }
140
141 View Code Duplication
        foreach ($items as $item) {
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...
142
            if (null !== $item->getParentId()) {
143
                $children[$item->getParentId()][] = $item;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$children was never initialized. Although not strictly required by PHP, it is generally a good practice to add $children = 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...
144
            }
145
        }
146
147
        // loop will be false if the root has no children (i.e., an empty menu!)
148
        $loop = !empty($children[$root_id]);
149
150
        // initializing $parent as the root
151
        $parent = $root_id;
152
        $parent_stack = array();
153
154
        $html = [];
155
156
        // HTML wrapper for the menu (open)
157
        $html[] = '<ul>';
158
159
        $html[] = !empty($before['first_root_li']) ? str_repeat("\t", $nesting + 1).$before['first_root_li'] : '';
0 ignored issues
show
Bug introduced by
The variable $before seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
160
161
        // loop
162
        while ($loop && (($item = each($children[$parent])) || ($parent > $root_id))) {
0 ignored issues
show
Bug introduced by
The variable $children 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...
163 View Code Duplication
            if (is_object($item['value'])) {
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...
164
                /**
165
                 * @var MenuItem $obj
166
                 */
167
                $obj = $item['value'];
168
                $item = [
169
                    'id' => $obj->getId(),
170
                    'parent_id' => $obj->getParentId(),
171
                    'title' => $obj->getTitle(),
172
                    'slug' => $obj->getSlug(),
173
                    'caption' => $obj->getCaption(),
174
                    'position' => $obj->getPosition(),
175
                ];
176
            }
177
178
            // HTML for menu item containing children (close)
179
            if ($item === false) {
180
                $parent = array_pop($parent_stack);
181
                $html[] = str_repeat("\t", (count($parent_stack) + 1) * 2 + $nesting).'</ul>';
182
                $html[] = str_repeat("\t", (count($parent_stack) + 1) * 2 - 1 + $nesting).'</li>';
183
            }
184
185
            // HTML for menu item containing children (open)
186
            elseif (!empty($children[$item['id']])) {
187
                $tab = str_repeat("\t", (count($parent_stack) + 1) * 2 - 1 + $nesting);
188
189
                /*
190
                 * <li> with <ul>
191
                 */
192
                $html[] = sprintf(
193
                    '%1$s'.'<li>%2$s - <a'.'%3$s'.' href="'.'%4$s'.'">%5$s</a> – pozycja: %6$s'.
194
                    ' <a href="/admin/appearance/menu/edit/%2$s" class="btn btn-primary btn-xs">Edytuj</a>'.
195
                    ' <a href="/admin/appearance/menu/del/%2$s" class="btn btn-danger btn-xs">Usuń</a>',
196
                    # %1$s tabulation
197
                    $tab,
198
199
                    $item['id'],
200
201
                    # %2$s a title=""
202
                    $this->isAttribute('title', $item['caption']),
203
204
                    # %3$s a href=""
205
                    $item['slug'],
206
207
                    # %4$s text inside item
208
                    $item['title'],
209
210
                    $item['position']
211
                );
212
213
                /*
214
                 * sub <ul> in <li>
215
                 */
216
                $html[] = sprintf(
217
                    '%1$s'.'<ul>',
218
                    # %1$s tabulation
219
                    $tab."\t"
220
                );
221
222
                $parent_stack[] = $item['parent_id'];
223
                $parent         = $item['id'];
224
            }
225
226
            // HTML for menu item with no children (aka "leaf")
227
            else {
228
                $html[] = sprintf(
229
                    '%1$s'.'<li>%2$s - <a'.'%3$s'.' href="'.'%4$s'.'">%5$s</a> – pozycja: %6$s'.
230
                    ' <a href="/admin/appearance/menu/edit/%2$s" class="btn btn-primary btn-xs">Edytuj</a>'.
231
                    ' <a href="/admin/appearance/menu/del/%2$s" class="btn btn-danger btn-xs">Edytuj</a>',
232
233
                    # %1$s tabulation
234
                    str_repeat("\t", (count($parent_stack) + 1) * 2 - 1 + $nesting),
235
236
                    $item['id'],
237
238
                    # %2$s a title=""
239
                    $this->isAttribute('title', $item['caption']),
240
241
                    # %3$s a href=""
242
                    $item['slug'],
243
244
                    # %4$s text inside item
245
                    $item['title'],
246
247
                    $item['position']
248
                );
249
            }
250
        }
251
252
        // HTML wrapper for the menu (close)
253
        $html[] = str_repeat("\t", $nesting).'</ul>';
254
255
        return implode("\n", array_filter($html))."\n";
256
    }
257
}
258