Passed
Push — master ( 2301b1...386ec7 )
by Alexander
14:22 queued 11:36
created

Dropdown::render()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Bootstrap5;
6
7
use JsonException;
8
use RuntimeException;
9
use Yiisoft\Arrays\ArrayHelper;
10
use Yiisoft\Definitions\Exception\InvalidConfigException;
11
use Yiisoft\Html\Html;
12
use Yiisoft\Html\Tag\Li;
13
14
use function array_key_exists;
15
use function array_merge;
16
use function array_merge_recursive;
17
use function is_string;
18
19
/**
20
 * Dropdown renders a Bootstrap dropdown menu component.
21
 *
22
 * For example,
23
 *
24
 * ```php
25
 * <div class="dropdown">
26
 *     <?php
27
 *         echo Dropdown::widget()
28
 *             ->items([
29
 *                 ['label' => 'DropdownA', 'url' => '/'],
30
 *                 ['label' => 'DropdownB', 'url' => '#'],
31
 *             ]);
32
 *     ?>
33
 * </div>
34
 * ```
35
 */
36
final class Dropdown extends Widget
37
{
38
    private array $items = [];
39
    private bool $encodeLabels = true;
40
    private bool $encodeTags = false;
41
    private array $submenuOptions = [];
42
    private array $options = [];
43
    private array $itemOptions = [];
44
    private array $linkOptions = [];
45
46 31
    public function render(): string
47
    {
48 31
        if (!isset($this->options['id'])) {
49 30
            $this->options['id'] = "{$this->getId()}-dropdown";
50
        }
51
52
        /** @psalm-suppress InvalidArgument */
53 31
        Html::addCssClass($this->options, ['widget' => 'dropdown-menu']);
54
55 31
        return $this->renderItems($this->items, $this->options);
56
    }
57
58
    /**
59
     * List of menu items in the dropdown. Each array element can be either an HTML string, or an array representing a
60
     * single menu with the following structure:
61
     *
62
     * - label: string, required, the label of the item link.
63
     * - encode: bool, optional, whether to HTML-encode item label.
64
     * - url: string|array, optional, the URL of the item link. This will be processed by {@see currentPath}.
65
     *   If not set, the item will be treated as a menu header when the item has no sub-menu.
66
     * - visible: bool, optional, whether this menu item is visible. Defaults to true.
67
     * - linkOptions: array, optional, the HTML attributes of the item link.
68
     * - options: array, optional, the HTML attributes of the item.
69
     * - items: array, optional, the submenu items. The structure is the same as this property.
70
     *   Note that Bootstrap doesn't support dropdown submenu. You have to add your own CSS styles to support it.
71
     * - submenuOptions: array, optional, the HTML attributes for sub-menu container tag. If specified it will be
72
     *   merged with {@see submenuOptions}.
73
     *
74
     * To insert divider use `-`.
75
     *
76
     * @param array $value
77
     */
78 31
    public function items(array $value): self
79
    {
80 31
        $new = clone $this;
81 31
        $new->items = $value;
82
83 31
        return $new;
84
    }
85
86
    /**
87
     * When tags Labels HTML should not be encoded.
88
     */
89 4
    public function withoutEncodeLabels(): self
90
    {
91 4
        $new = clone $this;
92 4
        $new->encodeLabels = false;
93
94 4
        return $new;
95
    }
96
97
    /**
98
     * The HTML attributes for sub-menu container tags.
99
     */
100 4
    public function submenuOptions(array $value): self
101
    {
102 4
        $new = clone $this;
103 4
        $new->submenuOptions = $value;
104
105 4
        return $new;
106
    }
107
108
    /**
109
     * @param array $value the HTML attributes for the widget container tag. The following special options are
110
     * recognized.
111
     *
112
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
113
     */
114 19
    public function options(array $value): self
115
    {
116 19
        $new = clone $this;
117 19
        $new->options = $value;
118
119 19
        return $new;
120
    }
121
122
    /**
123
     * Options for each item if not present in self
124
     */
125 1
    public function itemOptions(array $options): self
126
    {
127 1
        $new = clone $this;
128 1
        $new->itemOptions = $options;
129
130 1
        return $new;
131
    }
132
133
    /**
134
     * Options for each item link if not present in current item
135
     */
136 1
    public function linkOptions(array $options): self
137
    {
138 1
        $new = clone $this;
139 1
        $new->linkOptions = $options;
140
141 1
        return $new;
142
    }
143
144
    /**
145
     * Renders menu items.
146
     *
147
     * @param array $items the menu items to be rendered
148
     * @param array $options the container HTML attributes
149
     *
150
     * @throws InvalidConfigException|JsonException|RuntimeException if the label option is not specified in one of the
151
     * items.
152
     *
153
     * @return string the rendering result.
154
     */
155 31
    private function renderItems(array $items, array $options = []): string
156
    {
157 31
        $lines = [];
158
159 31
        foreach ($items as $item) {
160 31
            if (is_string($item)) {
161 4
                $item = ['label' => $item, 'encode' => false, 'enclose' => false];
162
            }
163
164 31
            if (isset($item['visible']) && !$item['visible']) {
165 3
                continue;
166
            }
167
168 31
            if (!array_key_exists('label', $item)) {
169 1
                throw new RuntimeException("The 'label' option is required.");
170
            }
171
172 30
            $lines[] = $this->renderItem($item);
173
        }
174
175 30
        $options = array_merge(['aria-expanded' => 'false'], $options);
176
177 30
        return Html::ul()
178 30
            ->items(...$lines)
179 30
            ->attributes($options)
180 30
            ->render();
181
    }
182
183
    /**
184
     * Render current dropdown item
185
     */
186 30
    private function renderItem(array $item): Li
187
    {
188 30
        $url = $item['url'] ?? null;
189 30
        $encodeLabel = $item['encode'] ?? $this->encodeLabels;
190 30
        $label = $encodeLabel ? Html::encode($item['label']) : $item['label'];
191 30
        $itemOptions = ArrayHelper::getValue($item, 'options', $this->itemOptions);
192 30
        $linkOptions = ArrayHelper::getValue($item, 'linkOptions', $this->linkOptions);
193 30
        $active = ArrayHelper::getValue($item, 'active', false);
194 30
        $disabled = ArrayHelper::getValue($item, 'disabled', false);
195 30
        $enclose = ArrayHelper::getValue($item, 'enclose', true);
196
197 30
        if ($url !== null) {
198 19
            Html::addCssClass($linkOptions, ['widget' => 'dropdown-item']);
199
200 19
            if ($disabled) {
201 2
                ArrayHelper::setValue($linkOptions, 'tabindex', '-1');
202 2
                ArrayHelper::setValue($linkOptions, 'aria-disabled', 'true');
203 2
                Html::addCssClass($linkOptions, ['disable' => 'disabled']);
204 19
            } elseif ($active) {
205 1
                Html::addCssClass($linkOptions, ['active' => 'active']);
206
            }
207
        }
208
209
        /** @psalm-suppress ConflictingReferenceConstraint */
210 30
        if (empty($item['items'])) {
211 30
            if ($url !== null) {
212 19
                $content = Html::a($label, $url, $linkOptions)->encode($this->encodeTags);
213 18
            } elseif ($label === '-') {
214 4
                Html::addCssClass($linkOptions, ['widget' => 'dropdown-divider']);
215 4
                $content = Html::tag('hr', '', $linkOptions);
216 16
            } elseif ($enclose === false) {
217 1
                $content = $label;
218
            } else {
219 15
                Html::addCssClass($linkOptions, ['widget' => 'dropdown-header']);
220 15
                $tag = ArrayHelper::remove($linkOptions, 'tag', 'h6');
221 15
                $content = Html::tag($tag, $label, $linkOptions);
222
            }
223
224 30
            return Li::tag()
225 30
                ->content($content)
226 30
                ->attributes($itemOptions)
227 30
                ->encode(false);
228
        }
229
230 4
        $submenuOptions = $this->submenuOptions;
231
232 4
        if (isset($item['submenuOptions'])) {
233 1
            $submenuOptions = array_merge($submenuOptions, $item['submenuOptions']);
234
        }
235
236 4
        Html::addCssClass($submenuOptions, ['submenu' => 'dropdown-menu']);
237 4
        Html::addCssClass($linkOptions, [
238 4
            'widget' => 'dropdown-item',
239 4
            'toggle' => 'dropdown-toggle',
240 4
        ]);
241
242 4
        $itemOptions = array_merge_recursive(['class' => ['dropdown'], 'aria-expanded' => 'false'], $itemOptions);
243
244 4
        $dropdown = self::widget()
245 4
            ->items($item['items'])
0 ignored issues
show
Bug introduced by
The method items() does not exist on Yiisoft\Widget\Widget. It seems like you code against a sub-type of Yiisoft\Widget\Widget such as Yiisoft\Yii\Bootstrap5\Nav or Yiisoft\Yii\Bootstrap5\Carousel or Yiisoft\Yii\Bootstrap5\Dropdown or Yiisoft\Yii\Bootstrap5\Tabs or Yiisoft\Yii\Bootstrap5\Accordion. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

245
            ->/** @scrutinizer ignore-call */ items($item['items'])
Loading history...
246 4
            ->options($submenuOptions)
247 4
            ->submenuOptions($submenuOptions);
248
249 4
        if ($this->encodeLabels === false) {
250 1
            $dropdown = $dropdown->withoutEncodeLabels();
251
        }
252
253 4
        ArrayHelper::setValue($linkOptions, 'data-bs-toggle', 'dropdown');
254 4
        ArrayHelper::setValue($linkOptions, 'data-bs-auto-close', 'outside');
255 4
        ArrayHelper::setValue($linkOptions, 'aria-haspopup', 'true');
256 4
        ArrayHelper::setValue($linkOptions, 'aria-expanded', 'false');
257 4
        ArrayHelper::setValue($linkOptions, 'role', 'button');
258
259 4
        $toggle = Html::a($label, $url, $linkOptions)->encode($this->encodeTags);
260
261 4
        return Li::tag()
262 4
            ->content($toggle . $dropdown->render())
263 4
            ->attributes($itemOptions)
264 4
            ->encode(false);
265
    }
266
}
267