Navigation   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 151
Duplicated Lines 19.87 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
dl 30
loc 151
rs 10
c 0
b 0
f 0
wmc 16
lcom 1
cbo 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
C create() 19 122 11
A isAttribute() 11 11 5

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace Rudolf\Modules\Appearance\Menu;
4
5
use Rudolf\Component\Helpers\Navigation\MenuItem;
6
use Rudolf\Component\Html\Navigation as BaseNavigation;
7
8
class Navigation extends BaseNavigation
9
{
10
    /**
11
     * Menu creator.
12
     * @link   http://pastebin.com/GAFvSew4
13
     * @author J. Bruni - original author
14
     * @return string|bool
15
     */
16
    public function create()
17
    {
18
        $root_id = $this->getRootID();
19
        $items   = $this->sortItems($this->getItems());
20
        $nesting = $this->getNesting();
21
22
        if (empty($items)) {
23
            return false;
24
        }
25
26 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...
27
            if (null !== $item->getParentId()) {
28
                $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...
29
            }
30
        }
31
32
        // loop will be false if the root has no children (i.e., an empty menu!)
33
        $loop = !empty($children[$root_id]);
34
35
        // initializing $parent as the root
36
        $parent       = $root_id;
37
        $parent_stack = [];
38
39
        $html = [];
40
41
        // HTML wrapper for the menu (open)
42
        $html[] = '<ul>';
43
44
        $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...
45
46
        // loop
47
        while ($loop && (($item = $this->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...
48 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...
49
                /**
50
                 * @var MenuItem $obj
51
                 */
52
                $obj  = $item['value'];
53
                $item = [
54
                    'id'        => $obj->getId(),
55
                    'parent_id' => $obj->getParentId(),
56
                    'title'     => $obj->getTitle(),
57
                    'slug'      => $obj->getSlug(),
58
                    'caption'   => $obj->getCaption(),
59
                    'position'  => $obj->getPosition(),
60
                ];
61
            }
62
63
            // HTML for menu item containing children (close)
64
            if ($item === false) {
65
                $parent = array_pop($parent_stack);
66
                $html[] = str_repeat("\t", (count($parent_stack) + 1) * 2 + $nesting).'</ul>';
67
                $html[] = str_repeat("\t", (count($parent_stack) + 1) * 2 - 1 + $nesting).'</li>';
68
            } // HTML for menu item containing children (open)
69
            elseif (!empty($children[$item['id']])) {
70
                $tab = str_repeat("\t", (count($parent_stack) + 1) * 2 - 1 + $nesting);
71
72
                /*
73
                 * <li> with <ul>
74
                 */
75
                $html[] = sprintf(
76
                    '%1$s'.'<li>%2$s - <a'.'%3$s'.' href="'.'%4$s'.'">%5$s</a> – pozycja: %6$s'.
77
                    ' <a href="'.DIR.'/admin/appearance/menu/edit-item/%2$s" class="btn btn-primary btn-xs">Edytuj</a>'.
78
                    ' <a href="'.DIR.'/admin/appearance/menu/del-item/%2$s" class="btn btn-danger btn-xs">Usuń</a>',
79
                    # %1$s tabulation
80
                    $tab,
81
82
                    $item['id'],
83
84
                    # %2$s a title=""
85
                    $this->isAttribute('title', $item['caption']),
86
87
                    # %3$s a href=""
88
                    $item['slug'],
89
90
                    # %4$s text inside item
91
                    $item['title'],
92
93
                    $item['position']
94
                );
95
96
                /*
97
                 * sub <ul> in <li>
98
                 */
99
                $html[] = sprintf(
100
                    '%1$s'.'<ul>',
101
                    # %1$s tabulation
102
                    $tab."\t"
103
                );
104
105
                $parent_stack[] = $item['parent_id'];
106
                $parent         = $item['id'];
107
            } // HTML for menu item with no children (aka "leaf")
108
            else {
109
                $html[] = sprintf(
110
                    '%1$s'.'<li>%2$s - <a'.'%3$s'.' href="'.'%4$s'.'">%5$s</a> – pozycja: %6$s'.
111
                    ' <a href="'.DIR.'/admin/appearance/menu/edit-item/%2$s" class="btn btn-primary btn-sm btn-xs">Edytuj</a>'.
112
                    ' <a href="'.DIR.'/admin/appearance/menu/del-item/%2$s" class="btn btn-danger btn-sm btn-xs">Usuń</a>',
113
114
                    # %1$s tabulation
115
                    str_repeat("\t", (count($parent_stack) + 1) * 2 - 1 + $nesting),
116
117
                    $item['id'],
118
119
                    # %2$s a title=""
120
                    $this->isAttribute('title', $item['caption']),
121
122
                    # %3$s a href=""
123
                    $item['slug'],
124
125
                    # %4$s text inside item
126
                    $item['title'],
127
128
                    $item['position']
129
                );
130
            }
131
        }
132
133
        // HTML wrapper for the menu (close)
134
        $html[] = str_repeat("\t", $nesting).'</ul>';
135
136
        return implode("\n", array_filter($html))."\n";
137
    }
138
139
    /**
140
     * Put value is not empty.
141
     *
142
     * @param string       $attribute
143
     * @param string|array $value
144
     *
145
     * @return string
146
     */
147 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...
Bug introduced by
Consider using a different method name as you override a private method of the parent class.

Overwriting private methods is generally fine as long as you also use private visibility. It might still be preferable for understandability to use a different method name.

Loading history...
148
    {
149
        if (is_array($value)) {
150
            array_filter($value);
151
            $value = trim(implode(' ', $value));
152
153
            return !empty($value) ? ' '.$attribute.'="'.$value.'"' : '';
154
        }
155
156
        return (isset($value) and !empty($value)) ? ' '.$attribute.'="'.trim($value).'"' : '';
157
    }
158
}
159