Passed
Push — master ( 566566...d0f53d )
by Alexander
02:18
created

Accordion::withoutEncodeLabels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
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\Html\Html;
11
12
use function array_column;
13
use function array_key_exists;
14
use function array_merge;
15
use function array_search;
16
use function implode;
17
use function is_array;
18
use function is_numeric;
19
use function is_object;
20
use function is_string;
21
22
/**
23
 * Accordion renders an accordion bootstrap javascript component.
24
 *
25
 * For example:
26
 *
27
 * ```php
28
 * echo Accordion::widget()
29
 *     ->items([
30
 *         [
31
 *             'label' => 'Collapsible Group Item #1',
32
 *             'content' => 'Anim pariatur cliche...',
33
 *             // open its content by default
34
 *             'contentOptions' => ['class' => 'show'],
35
 *         ],
36
 *         // another group item
37
 *         [
38
 *             'label' => 'Collapsible Group Item #2',
39
 *             'content' => 'Anim pariatur cliche...',
40
 *             'contentOptions' => [...],
41
 *             'options' => [...],
42
 *             'expand' => true,
43
 *         ],
44
 *         // if you want to swap out .accordion-body with .list-group, you may provide an array
45
 *         [
46
 *             'label' => 'Collapsible Group Item #3',
47
 *             'content' => [
48
 *                 'Anim pariatur cliche...',
49
 *                 'Anim pariatur cliche...',
50
 *             ],
51
 *             'contentOptions' => [...],
52
 *             'options' => [...],
53
 *         ],
54
 *     ]);
55
 * ```
56
 */
57
final class Accordion extends Widget
58
{
59
    private array $items = [];
60
    private bool $encodeLabels = true;
61
    private bool $encodeTags = false;
62
    private bool $autoCloseItems = true;
63
    private array $itemToggleOptions = [];
64
    private array $options = [];
65
66 11
    protected function run(): string
67
    {
68 11
        if (!isset($this->options['id'])) {
69 11
            $this->options['id'] = "{$this->getId()}-accordion";
70
        }
71
72
        /** @psalm-suppress InvalidArgument */
73 11
        Html::addCssClass($this->options, ['widget' => 'accordion']);
74
75 11
        if ($this->encodeTags === false) {
76 10
            $this->options['encode'] = false;
77
        }
78
79 11
        return Html::div($this->renderItems(), $this->options);
80
    }
81
82
    /**
83
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
84
     *
85
     * Set this to `false` to allow keeping multiple items open at once.
86
     *
87
     * @return $this
88
     */
89 1
    public function allowMultipleOpenedItems(): self
90
    {
91 1
        $new = clone $this;
92 1
        $new->autoCloseItems = false;
93
94 1
        return $new;
95
    }
96
97
    /**
98
     * When tags Labels HTML should not be encoded.
99
     *
100
     * @return $this
101
     */
102 1
    public function withoutEncodeLabels(): self
103
    {
104 1
        $new = clone $this;
105 1
        $new->encodeLabels = false;
106
107 1
        return $new;
108
    }
109
110
    /**
111
     * List of groups in the collapse widget. Each array element represents a single group with the following structure:
112
     *
113
     * - label: string, required, the group header label.
114
     * - encode: bool, optional, whether this label should be HTML-encoded. This param will override global
115
     *   `$this->encodeLabels` param.
116
     * - content: array|string|object, required, the content (HTML) of the group
117
     * - options: array, optional, the HTML attributes of the group
118
     * - contentOptions: optional, the HTML attributes of the group's content
119
     *
120
     * You may also specify this property as key-value pairs, where the key refers to the `label` and the value refers
121
     * to `content`. If value is a string it is interpreted as label. If it is an array, it is interpreted as explained
122
     * above.
123
     *
124
     * For example:
125
     *
126
     * ```php
127
     * echo Accordion::widget()
128
     *     ->items(
129
     *         [
130
     *             [
131
     *                 'Introduction' => 'This is the first collapsible menu',
132
     *                 'Second panel' => [
133
     *                     'content' => 'This is the second collapsible menu',
134
     *                 ],
135
     *             ],
136
     *             [
137
     *                 'label' => 'Third panel',
138
     *                 'content' => 'This is the third collapsible menu',
139
     *             ],
140
     *         ],
141
     *     );
142
     * ```
143
     *
144
     * @param array $value
145
     *
146
     * @return $this
147
     */
148 11
    public function items(array $value): self
149
    {
150 11
        $new = clone $this;
151 11
        $new->items = $value;
152
153 11
        return $new;
154
    }
155
156
    /**
157
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
158
     *
159
     * For example:
160
     *
161
     * ```php
162
     * [
163
     *     'tag' => 'div',
164
     *     'class' => 'custom-toggle',
165
     * ]
166
     * ```
167
     *
168
     * @param array $value
169
     *
170
     * @return $this
171
     */
172 1
    public function itemToggleOptions(array $value): self
173
    {
174 1
        $new = clone $this;
175 1
        $new->itemToggleOptions = $value;
176
177 1
        return $new;
178
    }
179
180
    /**
181
     * The HTML attributes for the widget container tag. The following special options are recognized.
182
     *
183
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
184
     *
185
     * @param array $value
186
     *
187
     * @return $this
188
     */
189 1
    public function options(array $value): self
190
    {
191 1
        $new = clone $this;
192 1
        $new->options = $value;
193
194 1
        return $new;
195
    }
196
197
    /**
198
     * Allows you to enable the encoding tags html.
199
     *
200
     * @return self
201
     */
202 1
    public function encodeTags(): self
203
    {
204 1
        $new = clone $this;
205 1
        $new->encodeTags = true;
206
207 1
        return $new;
208
    }
209
210
    /**
211
     * Renders collapsible items as specified on {@see items}.
212
     *
213
     * @throws JsonException|RuntimeException
214
     *
215
     * @return string the rendering result
216
     */
217 11
    private function renderItems(): string
218
    {
219 11
        $items = [];
220 11
        $index = 0;
221 11
        $expanded = array_search(true, array_column($this->items, 'expand'), true);
222
223 11
        foreach ($this->items as $key => $item) {
224 11
            if (!is_array($item)) {
225 1
                $item = ['content' => $item];
226
            }
227
228 11
            if ($expanded === false && $index === 0) {
229 10
                $item['expand'] = true;
230
            }
231
232 11
            if (!array_key_exists('label', $item)) {
233 3
                throw new RuntimeException('The "label" option is required.');
234
            }
235
236 8
            $header = ArrayHelper::remove($item, 'label');
237 8
            $options = ArrayHelper::getValue($item, 'options', []);
238
239 8
            if ($this->encodeTags === false) {
240 7
                $options['encode'] = false;
241
            }
242
243 8
            Html::addCssClass($options, ['panel' => 'accordion-item']);
244
245 8
            $items[] = Html::div($this->renderItem($header, $item, $index++), $options);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type object; however, parameter $item of Yiisoft\Yii\Bootstrap5\Accordion::renderItem() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

245
            $items[] = Html::div($this->renderItem($header, /** @scrutinizer ignore-type */ $item, $index++), $options);
Loading history...
Bug introduced by
It seems like $header can also be of type null; however, parameter $header of Yiisoft\Yii\Bootstrap5\Accordion::renderItem() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

245
            $items[] = Html::div($this->renderItem(/** @scrutinizer ignore-type */ $header, $item, $index++), $options);
Loading history...
246
        }
247
248 7
        return implode("\n", $items);
249
    }
250
251
    /**
252
     * Renders a single collapsible item group.
253
     *
254
     * @param string $header a label of the item group {@see items}
255
     * @param array $item a single item from {@see items}
256
     * @param int $index the item index as each item group content must have an id
257
     *
258
     * @throws JsonException|RuntimeException
259
     *
260
     * @return string the rendering result
261
     */
262 8
    private function renderItem(string $header, array $item, int $index): string
263
    {
264 8
        if (array_key_exists('content', $item)) {
265 7
            $id = $this->options['id'] . '-collapse' . $index;
266 7
            $expand = ArrayHelper::remove($item, 'expand', false);
267 7
            $options = ArrayHelper::getValue($item, 'contentOptions', []);
268 7
            $options['id'] = $id;
269
270 7
            Html::addCssClass($options, ['widget' => 'accordion-body collapse']);
271
272 7
            if ($expand) {
273 7
                Html::addCssClass($options, ['visibility' => 'show']);
274
            }
275
276 7
            if (!isset($options['aria-label'], $options['aria-labelledby'])) {
277 7
                $options['aria-labelledby'] = $options['id'] . '-heading';
278
            }
279
280 7
            $encodeLabel = $item['encode'] ?? $this->encodeLabels;
281
282 7
            if ($encodeLabel) {
283 7
                $header = Html::encode($header);
284
            }
285
286 7
            $itemToggleOptions = array_merge([
287 7
                'tag' => 'button',
288 7
                'type' => 'button',
289 7
                'data-bs-toggle' => 'collapse',
290 7
                'data-bs-target' => '#' . $options['id'],
291 7
                'aria-expanded' => $expand ? 'true' : 'false',
292 7
            ], $this->itemToggleOptions);
293
294 7
            if ($this->encodeTags === false) {
295 6
                $itemToggleOptions['encode'] = false;
296
            }
297
298 7
            $itemToggleTag = ArrayHelper::remove($itemToggleOptions, 'tag', 'button');
299
300
            /** @psalm-suppress ConflictingReferenceConstraint */
301 7
            if ($itemToggleTag === 'a') {
302 1
                ArrayHelper::remove($itemToggleOptions, 'data-bs-target');
303 1
                $header = Html::a($header, '#' . $id, $itemToggleOptions) . "\n";
304
            } else {
305 6
                Html::addCssClass($itemToggleOptions, ['widget' => 'accordion-button']);
306 6
                if (!$expand) {
307 6
                    Html::addCssClass($itemToggleOptions, ['expand' => 'collapsed']);
308
                }
309 6
                $header = Html::button($header, $itemToggleOptions);
310
            }
311
312 7
            if (is_string($item['content']) || is_numeric($item['content']) || is_object($item['content'])) {
313 7
                $content = $item['content'];
314 1
            } elseif (is_array($item['content'])) {
315 1
                $ulOptions = ['class' => 'list-group'];
316 1
                $ulItemOptions = ['itemOptions' => ['class' => 'list-group-item']];
317
318 1
                if ($this->encodeTags === false) {
319 1
                    $ulOptions['encode'] = false;
320 1
                    $ulItemOptions['itemOptions']['encode'] = false;
321
                }
322
323 1
                $content = Html::ul($item['content'], array_merge($ulOptions, $ulItemOptions)) . "\n";
324
            } else {
325 7
                throw new RuntimeException('The "content" option should be a string, array or object.');
326
            }
327
        } else {
328 1
            throw new RuntimeException('The "content" option is required.');
329
        }
330
331 7
        $group = [];
332
333 7
        if ($this->autoCloseItems) {
334 7
            $options['data-bs-parent'] = '#' . $this->options['id'];
335
        }
336
337 7
        $groupOptions = ['class' => 'accordion-header', 'id' => $options['id'] . '-heading'];
338
339 7
        if ($this->encodeTags === false) {
340 6
            $options['encode'] = false;
341 6
            $groupOptions['encode'] = false;
342
        }
343
344 7
        $group[] = Html::tag('h2', $header, $groupOptions);
345 7
        $group[] = Html::div($content, $options);
346
347 7
        return implode("\n", $group);
348
    }
349
}
350