Passed
Pull Request — master (#85)
by Albert
02:26
created

Accordion::renderCollapse()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 13
c 0
b 0
f 0
nc 8
nop 2
dl 0
loc 23
ccs 14
cts 14
cp 1
crap 4
rs 9.8333
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
use Yiisoft\Html\NoEncodeStringableInterface;
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 beforeRun(): bool
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 parent::beforeRun();
121
    }
122
123 13
    protected function run(): string
124
    {
125 13
        return Html::div($this->renderItems(), $this->options)
126 8
            ->encode($this->encodeTags)
127 8
            ->render();
128
    }
129
130
    /**
131
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
132
     *
133
     * Set this to `false` to allow keeping multiple items open at once.
134
     *
135
     * @return self
136
     */
137 1
    public function allowMultipleOpenedItems(): self
138
    {
139 1
        $new = clone $this;
140 1
        $new->autoCloseItems = false;
141
142 1
        return $new;
143
    }
144
145
    /**
146
     * When tags Labels HTML should not be encoded.
147
     *
148
     * @return self
149
     */
150 1
    public function withoutEncodeLabels(): self
151
    {
152 1
        $new = clone $this;
153 1
        $new->encodeLabels = false;
154
155 1
        return $new;
156
    }
157
158
    /**
159
     * List of groups in the collapse widget. Each array element represents a single group with the following structure:
160
     *
161
     * - label: string, required, the group header label.
162
     * - encode: bool, optional, whether this label should be HTML-encoded. This param will override global
163
     *   `$this->encodeLabels` param.
164
     * - content: array|string|object, required, the content (HTML) of the group
165
     * - options: array, optional, the HTML attributes of the group
166
     * - contentOptions: optional, the HTML attributes of the group's content
167
     *
168
     * You may also specify this property as key-value pairs, where the key refers to the `label` and the value refers
169
     * to `content`. If value is a string it is interpreted as label. If it is an array, it is interpreted as explained
170
     * above.
171
     *
172
     * For example:
173
     *
174
     * ```php
175
     * echo Accordion::widget()
176
     *     ->items(
177
     *         [
178
     *             [
179
     *                 'Introduction' => 'This is the first collapsible menu',
180
     *                 'Second panel' => [
181
     *                     'content' => 'This is the second collapsible menu',
182
     *                 ],
183
     *             ],
184
     *             [
185
     *                 'label' => 'Third panel',
186
     *                 'content' => 'This is the third collapsible menu',
187
     *             ],
188
     *         ],
189
     *     );
190
     * ```
191
     *
192
     * @param array $value
193
     *
194
     * @return self
195
     */
196 13
    public function items(array $value): self
197
    {
198 13
        $new = clone $this;
199 13
        $new->items = $value;
200 13
        $new->expands = array_map(fn ($item) => isset($item['expand']) ? (bool) $item['expand'] : $this->defaultExpand, $new->items);
201
202 13
        return $new;
203
    }
204
205
    /**
206
     * Set expand property for items without it
207
     *
208
     * @param bool|null $default
209
     *
210
     * @return self
211
     */
212 1
    public function defaultExpand(?bool $default): self
213
    {
214 1
        if ($default === $this->defaultExpand) {
215
            return $this;
216
        }
217
218 1
        $new = clone $this;
219 1
        $new->defaultExpand = $default;
220 1
        $new->expands = array_map(fn ($item) => isset($item['expand']) ? (bool) $item['expand'] : $new->defaultExpand, $new->items);
221
222 1
        return $new;
223
    }
224
225
    /**
226
     * Options for each header if not present in item
227
     *
228
     * @param array $options
229
     *
230
     * @return self
231
     */
232
    public function headerOptions(array $options): self
233
    {
234
        $new = clone $this;
235
        $new->headerOptions = $options;
236
237
        return $new;
238
    }
239
240
    /**
241
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
242
     *
243
     * For example:
244
     *
245
     * ```php
246
     * [
247
     *     'tag' => 'div',
248
     *     'class' => 'custom-toggle',
249
     * ]
250
     * ```
251
     *
252
     * @param array $value
253
     *
254
     * @return self
255
     */
256 1
    public function itemToggleOptions(array $value): self
257
    {
258 1
        $new = clone $this;
259 1
        $new->itemToggleOptions = $value;
260
261 1
        return $new;
262
    }
263
264
    /**
265
     * Content options for items if not present in current
266
     *
267
     * @param array $options
268
     *
269
     * @return self
270
     */
271
    public function contentOptions(array $options): self
272
    {
273
        $new = clone $this;
274
        $new->contentOptions = $options;
275
276
        return $new;
277
    }
278
279
    /**
280
     * The HTML attributes for the widget container tag. The following special options are recognized.
281
     *
282
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
283
     *
284
     * @param array $value
285
     *
286
     * @return self
287
     */
288 1
    public function options(array $value): self
289
    {
290 1
        $new = clone $this;
291 1
        $new->options = $value;
292
293 1
        return $new;
294
    }
295
296
    /**
297
     * Remove the default background-color, some borders, and some rounded corners to render accordions
298
     * edge-to-edge with their parent container.
299
     *
300
     * @return self
301
     *
302
     * @link https://getbootstrap.com/docs/5.0/components/accordion/#flush
303
     */
304 1
    public function flush(): self
305
    {
306 1
        $new = clone $this;
307 1
        $new->flush = true;
308
309 1
        return $new;
310
    }
311
312
    /**
313
     * Renders collapsible items as specified on {@see items}.
314
     *
315
     * @throws JsonException|RuntimeException
316
     *
317
     * @return string the rendering result
318
     */
319 13
    private function renderItems(): string
320
    {
321 13
        $items = [];
322 13
        $index = 0;
323 13
        $expanded = in_array(true, $this->expands, true);
324 13
        $allClose = !$expanded && count($this->items) === count(array_filter($this->expands, fn ($expand) => $expand === false));
325
326 13
        foreach ($this->items as $item) {
327 13
            if (!is_array($item)) {
328 1
                $item = ['content' => $item];
329
            }
330
331 13
            if ($allClose === false && $expanded === false && $index === 0) {
332 11
                $item['expand'] = true;
333
            }
334
335 13
            if (!array_key_exists('label', $item)) {
336 3
                throw new RuntimeException('The "label" option is required.');
337
            }
338
339 10
            $options = ArrayHelper::getValue($item, 'options', []);
340 10
            $item = $this->renderItem($item, $index++);
341
342 8
            Html::addCssClass($options, ['panel' => 'accordion-item']);
343
344 8
            $items[] = Html::div($item, $options)->encode(false)->render();
345
        }
346
347 8
        return implode('', $items);
348
    }
349
350
    /**
351
     * Renders a single collapsible item group.
352
     *
353
     * @param string $label a label of the item group {@see items}
354
     * @param array $item a single item from {@see items}
355
     * @param int $index the item index as each item group content must have an id
356
     *
357
     * @throws JsonException|RuntimeException
358
     *
359
     * @return string the rendering result
360
     */
361 10
    private function renderItem(array $item, int $index): string
362
    {
363 10
        if (!array_key_exists('content', $item)) {
364 1
            throw new RuntimeException('The "content" option is required.');
365
        }
366
367 9
        $header = $this->renderHeader($item, $index);
368 9
        $collapse = $this->renderCollapse($item, $index);
369
370 8
        return $header . $collapse;
371
    }
372
373
    /**
374
     * Render collapse header
375
     *
376
     * @param array $item
377
     * @param int $index
378
     *
379
     * @return string
380
     */
381 9
    private function renderHeader(array $item, int $index): string
382
    {
383 9
        $options = ArrayHelper::getValue($item, 'headerOptions', $this->headerOptions);
384 9
        $tag = ArrayHelper::remove($options, 'tag', 'h2');
385 9
        $options['id'] = $this->getHeaderId($item, $index);
386 9
        $toggle = $this->renderToggle($item, $index);
387
388 9
        Html::addCssClass($options, ['widget' => 'accordion-header']);
389
390 9
        return Html::tag($tag, $toggle, $options)->encode(false)->render();
391
    }
392
393
    /**
394
     * Render collapse switcher
395
     *
396
     * @param array $item
397
     * @param int $index
398
     *
399
     * @return string
400
     */
401 9
    private function renderToggle(array $item, int $index): string
402
    {
403 9
        $label = $item['label'];
404 9
        $expand = $item['expand'] ?? false;
405 9
        $collapseId = $this->getCollapseId($item, $index);
406
407 9
        $options = array_merge(
408
            [
409 9
                'data-bs-toggle' => 'collapse',
410 9
                'aria-expanded' => $expand ? 'true' : 'false',
411
                'aria-controls' => $collapseId,
412
            ],
413 9
            $item['toggleOptions'] ?? $this->itemToggleOptions
414
        );
415 9
        $tag = ArrayHelper::remove($options, 'tag', 'button');
416 9
        $encode = ArrayHelper::remove($options, 'encode', $this->encodeLabels);
417
418 9
        Html::addCssClass($options, ['accordion-button']);
419
420 9
        if (!$expand) {
421 8
            Html::addCssClass($options, ['collapsed']);
422
        }
423
424 9
        if ($tag === 'a') {
425 1
            $options['href'] = '#' . $collapseId;
426
        } else {
427 8
            $options['data-bs-target'] = '#' . $collapseId;
428
429 8
            if ($tag === 'button' && !isset($options['type'])) {
430 8
                $options['type'] = 'button';
431
            }
432
        }
433
434 9
        return Html::tag($tag, $label, $options)->encode($encode)->render();
435
    }
436
437
    /**
438
     * Render collapse item
439
     *
440
     * @param array $item
441
     * @param int $index
442
     *
443
     * @return string
444
     */
445 9
    private function renderCollapse(array $item, int $index): string
446
    {
447 9
        $expand = $item['expand'] ?? false;
448 9
        $options = $item['contentOptions'] ?? $this->contentOptions;
449 9
        $tag = ArrayHelper::remove($options, 'tag', 'div');
450 9
        $body = $this->renderBody($item);
451 8
        $options['id'] = $this->getCollapseId($item, $index);
452
453 8
        Html::addCssClass($options, ['accordion-collapse collapse']);
454
455 8
        if ($expand) {
456 7
            Html::addCssClass($options, ['show']);
457
        }
458
459 8
        if (!isset($options['aria-label'], $options['aria-labelledby'])) {
460 8
            $options['aria-labelledby'] = $this->getHeaderId($item, $index);
461
        }
462
463 8
        if ($this->autoCloseItems) {
464 8
            $options['data-bs-parent'] = '#' . $this->getId();
465
        }
466
467 8
        return Html::tag($tag, $body, $options)->encode(false)->render();
468
    }
469
470
    /**
471
     * Render collapse body
472
     *
473
     * @param array $item
474
     *
475
     * @return string
476
     */
477 9
    private function renderBody(array $item): string
478
    {
479 9
        $items = '';
480
481 9
        if (is_a($item['content'], NoEncodeStringableInterface::class)) {
482 1
            $content = [$item['content']];
483
        } else {
484 9
            $content = (array) $item['content'];
485
        }
486
487 9
        foreach ($content as $value) {
488 9
            if (!is_string($value) && !is_numeric($value) && !is_a($value, NoEncodeStringableInterface::class)) {
489 1
                throw new RuntimeException('The "content" option should be a string, array or object.');
490
            }
491
492 8
            $items .= (string) $value;
493
        }
494
495 8
        return Html::div($items, ['class' => 'accordion-body'])
496 8
            ->encode($this->encodeTags)
497 8
            ->render();
498
    }
499
}
500