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

Accordion::render()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 0
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 3
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_key_exists;
13
use function array_merge;
14
use function implode;
15
use function is_array;
16
use function is_numeric;
17
use function is_string;
18
19
/**
20
 * Accordion renders an accordion bootstrap JavaScript component.
21
 *
22
 * For example:
23
 *
24
 * ```php
25
 * echo Accordion::widget()
26
 *     ->items([
27
 *         [
28
 *             'label' => 'Accordion Item #1',
29
 *             'content' => [
30
 *                 'This is the first items accordion body. It is shown by default, until the collapse plugin ' .
31
 *                 'the appropriate classes that we use to style each element. These classes control the ' .
32
 *                 'overall appearance, as well as the showing and hiding via CSS transitions. You can  ' .
33
 *                 'modify any of this with custom CSS or overriding our default variables. Its also worth ' .
34
 *                 'noting that just about any HTML can go within the .accordion-body, though the transition ' .
35
 *                 'does limit overflow.',
36
 *             ],
37
 *         ],
38
 *         [
39
 *             'label' => 'Accordion Item #2',
40
 *             'content' => '<strong>This is the second items accordion body.</strong> It is hidden by default, ' .
41
 *                 'until the collapse plugin adds the appropriate classes that we use to style each element. ' .
42
 *                 'These classes control the overall appearance, as well as the showing and hiding via CSS ' .
43
 *                 'transitions. You can modify any of this with custom CSS or overriding our default ' .
44
 *                 'variables. Its also worth noting that just about any HTML can go within the ' .
45
 *                 '<code>.accordion-body</code>, though the transition does limit overflow.',
46
 *             'contentOptions' => [
47
 *                 'class' => 'testContentOptions',
48
 *             ],
49
 *             'options' => [
50
 *                 'class' => 'testClass',
51
 *                 'id' => 'testId',
52
 *             ],
53
 *         ],
54
 *         [
55
 *             'label' => '<b>Accordion Item #3</b>',
56
 *             'content' => [
57
 *                 '<b>test content1</b>',
58
 *                 '<strong>This is the third items accordion body.</strong> It is hidden by default, until the ' .
59
 *                 'collapse plugin adds the appropriate classes that we use to style each element. These ' .
60
 *                 'classes control the overall appearance, as well as the showing and hiding via CSS ' .
61
 *                 'transitions. You can modify any of this with custom CSS or overriding our default ' .
62
 *                 'variables. Its also worth noting that just about any HTML can go within the ' .
63
 *                 '<code>.accordion-body</code>, though the transition does limit overflow.',
64
 *             ],
65
 *             'contentOptions' => [
66
 *                 'class' => 'testContentOptions2',
67
 *             ],
68
 *             'options' => [
69
 *                 'class' => 'testClass2',
70
 *                 'id' => 'testId2',
71
 *             ],
72
 *             'encode' => false,
73
 *         ],
74
 *     ]);
75
 * ```
76
 *
77
 * @link https://getbootstrap.com/docs/5.0/components/accordion/
78
 */
79
final class Accordion extends Widget
80
{
81
    private array $items = [];
82
    private array $expands = [];
83
    private ?bool $defaultExpand = null;
84
    private bool $encodeLabels = true;
85
    private bool $encodeTags = false;
86
    private bool $autoCloseItems = true;
87
    private array $headerOptions = [];
88
    private array $itemToggleOptions = [];
89
    private array $contentOptions = [];
90
    private array $options = [];
91
    private bool $flush = false;
92
93 13
    public function getId(?string $suffix = '-accordion'): ?string
94
    {
95 13
        return $this->options['id'] ?? parent::getId($suffix);
96
    }
97
98 9
    private function getCollapseId(array $item, int $index): string
99
    {
100 9
        return ArrayHelper::getValueByPath($item, ['contentOptions', 'id'], $this->getId() . '-collapse' . $index);
101
    }
102
103 9
    private function getHeaderId(array $item, int $index): string
104
    {
105 9
        return ArrayHelper::getValueByPath($item, ['headerOptions', 'id'], $this->getCollapseId($item, $index) . '-heading');
106
    }
107
108 13
    public function render(): string
109
    {
110 13
        Html::addCssClass($this->options, ['widget' => 'accordion']);
111
112 13
        if ($this->flush) {
113 1
            Html::addCssClass($this->options, ['flush' => 'accordion-flush']);
114
        }
115
116 13
        if (!isset($this->options['id'])) {
117 13
            $this->options['id'] = $this->getId();
118
        }
119
120 13
        return Html::div($this->renderItems(), $this->options)
121 13
            ->encode($this->encodeTags)
122 13
            ->render();
123
    }
124
125
    /**
126
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
127
     *
128
     * Set this to `false` to allow keeping multiple items open at once.
129
     */
130 1
    public function allowMultipleOpenedItems(): self
131
    {
132 1
        $new = clone $this;
133 1
        $new->autoCloseItems = false;
134
135 1
        return $new;
136
    }
137
138
    /**
139
     * When tags Labels HTML should not be encoded.
140
     */
141 1
    public function withoutEncodeLabels(): self
142
    {
143 1
        $new = clone $this;
144 1
        $new->encodeLabels = false;
145
146 1
        return $new;
147
    }
148
149
    /**
150
     * List of groups in the collapse widget. Each array element represents a single group with the following structure:
151
     *
152
     * - label: string, required, the group header label.
153
     * - encode: bool, optional, whether this label should be HTML-encoded. This param will override global
154
     *   `$this->encodeLabels` param.
155
     * - content: array|string|object, required, the content (HTML) of the group
156
     * - options: array, optional, the HTML attributes of the group
157
     * - contentOptions: optional, the HTML attributes of the group's content
158
     *
159
     * You may also specify this property as key-value pairs, where the key refers to the `label` and the value refers
160
     * to `content`. If value is a string it is interpreted as label. If it is an array, it is interpreted as explained
161
     * above.
162
     *
163
     * For example:
164
     *
165
     * ```php
166
     * echo Accordion::widget()
167
     *     ->items(
168
     *         [
169
     *             [
170
     *                 'Introduction' => 'This is the first collapsible menu',
171
     *                 'Second panel' => [
172
     *                     'content' => 'This is the second collapsible menu',
173
     *                 ],
174
     *             ],
175
     *             [
176
     *                 'label' => 'Third panel',
177
     *                 'content' => 'This is the third collapsible menu',
178
     *             ],
179
     *         ],
180
     *     );
181
     * ```
182
     *
183
     * @param array $value
184
     */
185 13
    public function items(array $value): self
186
    {
187 13
        $new = clone $this;
188 13
        $new->items = $value;
189 13
        $new->expands = array_map(fn ($item) => isset($item['expand']) ? (bool) $item['expand'] : $this->defaultExpand, $new->items);
190
191 13
        return $new;
192
    }
193
194
    /**
195
     * Set expand property for items without it
196
     */
197 1
    public function defaultExpand(?bool $default): self
198
    {
199 1
        if ($default === $this->defaultExpand) {
200
            return $this;
201
        }
202
203 1
        $new = clone $this;
204 1
        $new->defaultExpand = $default;
205 1
        $new->expands = array_map(fn ($item) => isset($item['expand']) ? (bool) $item['expand'] : $new->defaultExpand, $new->items);
206
207 1
        return $new;
208
    }
209
210
    /**
211
     * Options for each header if not present in item
212
     */
213
    public function headerOptions(array $options): self
214
    {
215
        $new = clone $this;
216
        $new->headerOptions = $options;
217
218
        return $new;
219
    }
220
221
    /**
222
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
223
     *
224
     * For example:
225
     *
226
     * ```php
227
     * [
228
     *     'tag' => 'div',
229
     *     'class' => 'custom-toggle',
230
     * ]
231
     * ```
232
     *
233
     * @param array $value
234
     */
235 1
    public function itemToggleOptions(array $value): self
236
    {
237 1
        $new = clone $this;
238 1
        $new->itemToggleOptions = $value;
239
240 1
        return $new;
241
    }
242
243
    /**
244
     * Content options for items if not present in current
245
     */
246
    public function contentOptions(array $options): self
247
    {
248
        $new = clone $this;
249
        $new->contentOptions = $options;
250
251
        return $new;
252
    }
253
254
    /**
255
     * The HTML attributes for the widget container tag. The following special options are recognized.
256
     *
257
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
258
     *
259
     * @param array $value
260
     */
261 1
    public function options(array $value): self
262
    {
263 1
        $new = clone $this;
264 1
        $new->options = $value;
265
266 1
        return $new;
267
    }
268
269
    /**
270
     * Remove the default background-color, some borders, and some rounded corners to render accordions
271
     * edge-to-edge with their parent container.
272
     *
273
     * @link https://getbootstrap.com/docs/5.0/components/accordion/#flush
274
     */
275 1
    public function flush(): self
276
    {
277 1
        $new = clone $this;
278 1
        $new->flush = true;
279
280 1
        return $new;
281
    }
282
283
    /**
284
     * Renders collapsible items as specified on {@see items}.
285
     *
286
     * @throws JsonException|RuntimeException
287
     *
288
     * @return string the rendering result
289
     */
290 13
    private function renderItems(): string
291
    {
292 13
        $items = [];
293 13
        $index = 0;
294 13
        $expanded = in_array(true, $this->expands, true);
295 13
        $allClose = !$expanded && count($this->items) === count(array_filter($this->expands, fn ($expand) => $expand === false));
296
297 13
        foreach ($this->items as $item) {
298 13
            if (!is_array($item)) {
299 1
                $item = ['content' => $item];
300
            }
301
302 13
            if ($allClose === false && $expanded === false && $index === 0) {
303 11
                $item['expand'] = true;
304
            }
305
306 13
            if (!array_key_exists('label', $item)) {
307 3
                throw new RuntimeException('The "label" option is required.');
308
            }
309
310 10
            $options = ArrayHelper::getValue($item, 'options', []);
311 10
            $item = $this->renderItem($item, $index++);
312
313 8
            Html::addCssClass($options, ['panel' => 'accordion-item']);
314
315 8
            $items[] = Html::div($item, $options)
316 8
                ->encode(false)
317 8
                ->render();
318
        }
319
320 8
        return implode('', $items);
321
    }
322
323
    /**
324
     * Renders a single collapsible item group.
325
     *
326
     * @param array $item a single item from {@see items}
327
     * @param int $index the item index as each item group content must have an id
328
     *
329
     * @throws JsonException|RuntimeException
330
     *
331
     * @return string the rendering result
332
     */
333 10
    private function renderItem(array $item, int $index): string
334
    {
335 10
        if (!array_key_exists('content', $item)) {
336 1
            throw new RuntimeException('The "content" option is required.');
337
        }
338
339 9
        $header = $this->renderHeader($item, $index);
340 9
        $collapse = $this->renderCollapse($item, $index);
341
342 8
        return $header . $collapse;
343
    }
344
345
    /**
346
     * Render collapse header
347
     */
348 9
    private function renderHeader(array $item, int $index): string
349
    {
350 9
        $options = ArrayHelper::getValue($item, 'headerOptions', $this->headerOptions);
351 9
        $tag = ArrayHelper::remove($options, 'tag', 'h2');
352 9
        $options['id'] = $this->getHeaderId($item, $index);
353 9
        $toggle = $this->renderToggle($item, $index);
354
355 9
        Html::addCssClass($options, ['widget' => 'accordion-header']);
356
357 9
        return Html::tag($tag, $toggle, $options)
358 9
            ->encode(false)
359 9
            ->render();
360
    }
361
362
    /**
363
     * Render collapse switcher
364
     */
365 9
    private function renderToggle(array $item, int $index): string
366
    {
367 9
        $label = $item['label'];
368 9
        $expand = $item['expand'] ?? false;
369 9
        $collapseId = $this->getCollapseId($item, $index);
370
371 9
        $options = array_merge(
372 9
            [
373 9
                'data-bs-toggle' => 'collapse',
374 9
                'aria-expanded' => $expand ? 'true' : 'false',
375 9
                'aria-controls' => $collapseId,
376 9
            ],
377 9
            $item['toggleOptions'] ?? $this->itemToggleOptions
378 9
        );
379 9
        $tag = ArrayHelper::remove($options, 'tag', 'button');
380 9
        $encode = ArrayHelper::remove($options, 'encode', $this->encodeLabels);
381
382 9
        Html::addCssClass($options, ['accordion-button']);
383
384 9
        if (!$expand) {
385 8
            Html::addCssClass($options, ['collapsed']);
386
        }
387
388 9
        if ($tag === 'a') {
389 1
            $options['href'] = '#' . $collapseId;
390
        } else {
391 8
            $options['data-bs-target'] = '#' . $collapseId;
392
393 8
            if ($tag === 'button' && !isset($options['type'])) {
394 8
                $options['type'] = 'button';
395
            }
396
        }
397
398 9
        return Html::tag($tag, $label, $options)
399 9
            ->encode($encode)
400 9
            ->render();
401
    }
402
403
    /**
404
     * Render collapse item
405
     */
406 9
    private function renderCollapse(array $item, int $index): string
407
    {
408 9
        $expand = $item['expand'] ?? false;
409 9
        $options = $item['contentOptions'] ?? $this->contentOptions;
410 9
        $tag = ArrayHelper::remove($options, 'tag', 'div');
411 9
        $body = $this->renderBody($item);
412 8
        $options['id'] = $this->getCollapseId($item, $index);
413
414 8
        Html::addCssClass($options, ['accordion-collapse collapse']);
415
416 8
        if ($expand) {
417 7
            Html::addCssClass($options, ['show']);
418
        }
419
420 8
        if (!isset($options['aria-label'], $options['aria-labelledby'])) {
421 8
            $options['aria-labelledby'] = $this->getHeaderId($item, $index);
422
        }
423
424 8
        if ($this->autoCloseItems) {
425 8
            $options['data-bs-parent'] = '#' . $this->getId();
426
        }
427
428 8
        return Html::tag($tag, $body, $options)
429 8
            ->encode(false)
430 8
            ->render();
431
    }
432
433
    /**
434
     * Render collapse body
435
     */
436 9
    private function renderBody(array $item): string
437
    {
438 9
        $items = '';
439
440 9
        if ($this->isStringableObject($item['content'])) {
441 1
            $content = [$item['content']];
442
        } else {
443 9
            $content = (array) $item['content'];
444
        }
445
446 9
        foreach ($content as $value) {
447 9
            if (!is_string($value) && !is_numeric($value) && !$this->isStringableObject($value)) {
448 1
                throw new RuntimeException('The "content" option should be a string, array or object.');
449
            }
450
451 8
            $items .= $value;
452
        }
453
454 8
        return Html::div($items, ['class' => 'accordion-body'])
455 8
            ->encode($this->encodeTags)
456 8
            ->render();
457
    }
458
459 9
    private function isStringableObject(mixed $value): bool
460
    {
461 9
        return is_object($value) && method_exists($value, '__toString');
462
    }
463
}
464