Completed
Push — master ( 9a19e6...44bc09 )
by Mikołaj
06:44
created

Breadcrumbs::isAttribute()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 11

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 2
dl 11
loc 11
rs 9.6111
c 0
b 0
f 0
1
<?php
2
3
namespace Rudolf\Component\Html;
4
5
class Breadcrumbs
6
{
7
    /**
8
     * @var array
9
     */
10
    private $elements;
11
12
    /**
13
     * @var array
14
     */
15
    private $address;
16
17
    /**
18
     * @var array
19
     */
20
    private $classes;
21
22
    /**
23
     * @var int
24
     */
25
    private $nesting;
26
27
    /**
28
     * Constructor.
29
     *
30
     * @param array $elements Array with menu elements
31
     * @param array $address  Address elements array
32
     * @param array $classes  Array which classes to use in breadcrumbs
33
     * @param int   $nesting  Generated code nesting
34
     */
35
    public function __construct(array $elements = [], array $address = [], array $classes = [], $nesting = 0)
36
    {
37
        $this->setElements($elements);
38
        $this->setAddress($address);
39
        $this->setClasses($classes);
40
        $this->setNesting($nesting);
41
    }
42
43
    public function setElements(array $elements)
44
    {
45
        $this->elements = $elements;
46
    }
47
48
    public function getElements()
49
    {
50
        return $this->elements;
51
    }
52
53
    public function setAddress(array $address)
54
    {
55
        $this->address = $address;
56
    }
57
58
    public function getAddress()
59
    {
60
        return $this->address;
61
    }
62
63
    public function setClasses(array $classes)
64
    {
65
        $this->classes = array_merge([
66
            'ul' => '',
67
            'li' => '',
68
            'li_active' => '',
69
            'a' => '',
70
            'a_active' => '',
71
        ], $classes);
72
    }
73
74
    public function getClasses()
75
    {
76
        return $this->classes;
77
    }
78
79
    /**
80
     * @param int $nesting
81
     */
82
    public function setNesting($nesting)
83
    {
84
        $this->nesting = $nesting;
85
    }
86
87
    public function getNesting()
88
    {
89
        return $this->nesting;
90
    }
91
92
    public function getStructure()
93
    {
94
        $menu = $this->getElements();
95
        $address = $this->getAddress();
96
97
        if (empty($menu) || empty($address)) {
98
            return false;
99
        }
100
101
        $array = [];
102
103
        // temp workaround
104
        foreach ($menu as $key => $value) {
105
            if (isset($value['slug'])) {
106
                $array[$value['slug']][$value['parent_id']] = $value;
107
            }
108
        }
109
        if (isset($value['slug'])) {
110
            $menu = $array;
111
        }
112
113
        $url = null;
114
        $array = [];
115
116
        for ($pid = 0, $i = 0; $i < $c = count($address); ++$i) {
117
            if (isset($menu[$address[$i]][$pid]) && $pid === (int) $menu[$address[$i]][$pid]['parent_id']) {
118
                $array[$i] = array($url.'/'.$address[$i], $menu[$address[$i]][$pid]['title']);
119
                $pid = $menu[$address[$i]][$pid]['id'];
120
                $url .= '/'.$address[$i];
121
            }
122
        }
123
124
        return $array;
125
    }
126
127
    public function create($withStart = true)
128
    {
129
        $elements = $this->getStructure();
130
        if (empty($elements)) {
131
            return false;
132
        }
133
134
        $nesting = $this->getNesting();
135
        $classes = $this->getClasses();
136
137
        $html[] = sprintf(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$html was never initialized. Although not strictly required by PHP, it is generally a good practice to add $html = 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...
138
            '<ul%1$s>',
139
            $this->isAttribute('class', $classes['ul'])
140
        );
141
142
        $tab = str_repeat("\t", $nesting + 1);
143
144
        if (true === $withStart) {
145
            $html[] = sprintf(
146
                '%1$s<li%2$s><a%3$s href="%4$s/">Start</a></li>',
147
                $tab,
148
                $this->isAttribute('class', $classes['li']),
149
                $this->isAttribute('class', $classes['a']),
150
                DIR
151
            );
152
        }
153
154
        for ($i = 0; $i < (count($elements) - 1); ++$i) {
155
            $html[] = sprintf(
156
                '%1$s<li%2$s><a%3$s href="%4$s">%5$s</a></li>',
157
                $tab, // nesting
158
                $this->isAttribute('class', $classes['li']),
159
                $this->isAttribute('class', $classes['a']),
160
                DIR.$elements[$i][0],
161
                $elements[$i][1]
162
            );
163
        }
164
165
        $html[] = sprintf(
166
            '%1$s'.'<li'.'%2$s'.'>'.'%3$s'.'</li>',
167
            $tab, // nesting
168
            $this->isAttribute('class', [$classes['li'], $classes['li_active']]),
169
            $elements[$i][1]
170
        );
171
172
        $html[] = str_repeat("\t", $nesting).'</ul>';
173
174
        return implode("\n", $html);
175
    }
176
177
    /**
178
     * Put value is not empty.
179
     *
180
     * @param string       $attribute
181
     * @param string|array $value
182
     *
183
     * @return string
184
     */
185 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...
186
    {
187
        if (is_array($value)) {
188
            array_filter($value);
189
            $value = trim(implode(' ', $value));
190
191
            return !empty($value) ? ' '.$attribute.'="'.$value.'"' : '';
192
        }
193
194
        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...
195
    }
196
}
197