Passed
Pull Request — master (#71)
by
unknown
02:05
created

Accordion::allClose()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 0
dl 0
loc 11
ccs 6
cts 6
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_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' => 'Accordion Item #1',
32
 *             'content' => [
33
 *                 'This is the first items accordion body. It is shown by default, until the collapse plugin ' .
34
 *                 'the appropriate classes that we use to style each element. These classes control the ' .
35
 *                 'overall appearance, as well as the showing and hiding via CSS transitions. You can  ' .
36
 *                 'modify any of this with custom CSS or overriding our default variables. Its also worth ' .
37
 *                 'noting that just about any HTML can go within the .accordion-body, though the transition ' .
38
 *                 'does limit overflow.',
39
 *             ],
40
 *         ],
41
 *         [
42
 *             'label' => 'Accordion Item #2',
43
 *             'content' => '<strong>This is the second items accordion body.</strong> It is hidden by default, ' .
44
 *                 'until the collapse plugin adds the appropriate classes that we use to style each element. ' .
45
 *                 'These classes control the overall appearance, as well as the showing and hiding via CSS ' .
46
 *                 'transitions. You can modify any of this with custom CSS or overriding our default ' .
47
 *                 'variables. Its also worth noting that just about any HTML can go within the ' .
48
 *                 '<code>.accordion-body</code>, though the transition does limit overflow.',
49
 *             'contentOptions' => [
50
 *                 'class' => 'testContentOptions',
51
 *             ],
52
 *             'options' => [
53
 *                 'class' => 'testClass',
54
 *                 'id' => 'testId',
55
 *             ],
56
 *         ],
57
 *         [
58
 *             'label' => '<b>Accordion Item #3</b>',
59
 *             'content' => [
60
 *                 '<b>test content1</b>',
61
 *                 '<strong>This is the third items accordion body.</strong> It is hidden by default, until the ' .
62
 *                 'collapse plugin adds the appropriate classes that we use to style each element. These ' .
63
 *                 'classes control the overall appearance, as well as the showing and hiding via CSS ' .
64
 *                 'transitions. You can modify any of this with custom CSS or overriding our default ' .
65
 *                 'variables. Its also worth noting that just about any HTML can go within the ' .
66
 *                 '<code>.accordion-body</code>, though the transition does limit overflow.',
67
 *             ],
68
 *             'contentOptions' => [
69
 *                 'class' => 'testContentOptions2',
70
 *             ],
71
 *             'options' => [
72
 *                 'class' => 'testClass2',
73
 *                 'id' => 'testId2',
74
 *             ],
75
 *             'encode' => false,
76
 *         ],
77
 *     ]);
78
 * ```
79
 *
80
 * @link https://getbootstrap.com/docs/5.0/components/accordion/
81
 */
82
final class Accordion extends Widget
83
{
84
    private array $items = [];
85
    private bool $encodeLabels = true;
86
    private bool $encodeTags = false;
87
    private bool $autoCloseItems = true;
88
    private array $headerOptions = [];
89
    private array $itemToggleOptions = [];
90
    private array $contentOptions = [];
91
    private array $options = [];
92
    private bool $flush = false;
93
94 13
    public function getId(?string $suffix = '-accordion'): ?string
95
    {
96 13
        return $this->options['id'] ?? parent::getId($suffix);
97
    }
98
99 13
    public function beforeRun(): bool
100
    {
101 13
        Html::addCssClass($this->options, ['widget' => 'accordion']);
102
103 13
        if ($this->flush) {
104 1
            Html::addCssClass($this->options, ['flush' => 'accordion-flush']);
105
        }
106
107 13
        if (!isset($this->options['id'])) {
108 13
            $this->options['id'] = $this->getId();
109
        }
110
111 13
        return parent::beforeRun();
112
    }
113
114 13
    protected function run(): string
115
    {
116 13
        return Html::div($this->renderItems(), $this->options)
117 8
            ->encode($this->encodeTags)
118 8
            ->render();
119
    }
120
121
    /**
122
     * Whether to close other items if an item is opened. Defaults to `true` which causes an accordion effect.
123
     *
124
     * Set this to `false` to allow keeping multiple items open at once.
125
     *
126
     * @return self
127
     */
128 1
    public function allowMultipleOpenedItems(): self
129
    {
130 1
        $new = clone $this;
131 1
        $new->autoCloseItems = false;
132
133 1
        return $new;
134
    }
135
136
    /**
137
     * When tags Labels HTML should not be encoded.
138
     *
139
     * @return self
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
     * @return self
186
     */
187 13
    public function items(array $value): self
188
    {
189 13
        $new = clone $this;
190 13
        $new->items = $value;
191
192 13
        return $new;
193
    }
194
195
    /**
196
     * Options for each header if not present in item
197
     *
198
     * @param array $options
199
     *
200
     * @return self
201
     */
202
    public function headerOptions(array $options): self
203
    {
204
        $new = clone $this;
205
        $new->headerOptions = $options;
206
207
        return $new;
208
    }
209
210
    /**
211
     * The HTML options for the item toggle tag. Key 'tag' might be used here for the tag name specification.
212
     *
213
     * For example:
214
     *
215
     * ```php
216
     * [
217
     *     'tag' => 'div',
218
     *     'class' => 'custom-toggle',
219
     * ]
220
     * ```
221
     *
222
     * @param array $value
223
     *
224
     * @return self
225
     */
226 1
    public function itemToggleOptions(array $value): self
227
    {
228 1
        $new = clone $this;
229 1
        $new->itemToggleOptions = $value;
230
231 1
        return $new;
232
    }
233
234
    /**
235
     * Content options for items if not present in current
236
     *
237
     * @param array $options
238
     *
239
     * @return self
240
     */
241
    public function contentOptions(array $options): self
242
    {
243
        $new = clone $this;
244
        $new->contentOptions = $options;
245
246
        return $new;
247
    }
248
249
    /**
250
     * The HTML attributes for the widget container tag. The following special options are recognized.
251
     *
252
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
253
     *
254
     * @param array $value
255
     *
256
     * @return self
257
     */
258 1
    public function options(array $value): self
259
    {
260 1
        $new = clone $this;
261 1
        $new->options = $value;
262
263 1
        return $new;
264
    }
265
266
    /**
267
     * Remove the default background-color, some borders, and some rounded corners to render accordions
268
     * edge-to-edge with their parent container.
269
     *
270
     * @return self
271
     *
272
     * @link https://getbootstrap.com/docs/5.0/components/accordion/#flush
273
     */
274 1
    public function flush(): self
275
    {
276 1
        $new = clone $this;
277 1
        $new->flush = true;
278
279 1
        return $new;
280
    }
281
282
283 13
    private function expands(): array
284
    {
285 13
        return array_map(static fn ($item) => $item['expand'] ?? null, $this->items);
286
    }
287
288 13
    private function hasExpanded(): bool
289
    {
290 13
        return in_array(true, $this->expands(), true);
291
    }
292
293 13
    private function allClose(): bool
294
    {
295 13
        $expands = $this->expands();
296
297 13
        foreach ($expands as $value) {
298 13
            if ($value !== false) {
299 12
                return false;
300
            }
301
        }
302
303 1
        return true;
304
    }
305
306
    /**
307
     * Renders collapsible items as specified on {@see items}.
308
     *
309
     * @throws JsonException|RuntimeException
310
     *
311
     * @return string the rendering result
312
     */
313 13
    private function renderItems(): string
314
    {
315 13
        $items = [];
316 13
        $index = 0;
317 13
        $expanded = $this->hasExpanded();
318 13
        $allCLose = $this->allClose();
319
320 13
        foreach ($this->items as $item) {
321 13
            if (!is_array($item)) {
322 1
                $item = ['content' => $item];
323
            }
324
325 13
            if ($allCLose === false && $expanded === false && $index === 0) {
326 11
                $item['expand'] = true;
327
            }
328
329 13
            if (!array_key_exists('label', $item)) {
330 3
                throw new RuntimeException('The "label" option is required.');
331
            }
332
333 10
            $header = ArrayHelper::remove($item, 'label');
334 10
            $options = ArrayHelper::getValue($item, 'options', []);
335
336 10
            Html::addCssClass($options, ['panel' => 'accordion-item']);
337
338 10
            $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

338
            $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

338
            $items[] = Html::div($this->renderItem(/** @scrutinizer ignore-type */ $header, $item, $index++), $options)
Loading history...
339 8
                ->encode($this->encodeTags)
340 8
                ->render();
341
        }
342
343 8
        return implode("\n", $items);
344
    }
345
346
    /**
347
     * Renders a single collapsible item group.
348
     *
349
     * @param string $header a label of the item group {@see items}
350
     * @param array $item a single item from {@see items}
351
     * @param int $index the item index as each item group content must have an id
352
     *
353
     * @throws JsonException|RuntimeException
354
     *
355
     * @return string the rendering result
356
     */
357 10
    private function renderItem(string $header, array $item, int $index): string
358
    {
359 10
        if (array_key_exists('content', $item)) {
360 9
            $expand = ArrayHelper::remove($item, 'expand', false);
361 9
            $options = ArrayHelper::getValue($item, 'contentOptions', $this->contentOptions);
362 9
            $headerOptions = ArrayHelper::remove($item, 'headerOptions', $this->headerOptions);
0 ignored issues
show
Bug introduced by
It seems like $item can also be of type object; however, parameter $array of Yiisoft\Arrays\ArrayHelper::remove() 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

362
            $headerOptions = ArrayHelper::remove(/** @scrutinizer ignore-type */ $item, 'headerOptions', $this->headerOptions);
Loading history...
363
364 9
            if (!isset($options['id'])) {
365 9
                $options['id'] = $this->getId() . '-collapse' . $index;
366
            }
367
368 9
            if (!isset($headerOptions['id'])) {
369 9
                $headerOptions['id'] = $options['id'] . '-heading';
370
            }
371
372 9
            Html::addCssClass($headerOptions, ['widget' => 'accordion-header']);
373 9
            Html::addCssClass($options, ['widget' => 'accordion-collapse collapse']);
374
375 9
            if ($expand) {
376 8
                Html::addCssClass($options, ['visibility' => 'show']);
377
            }
378
379 9
            if (!isset($options['aria-label'], $options['aria-labelledby'])) {
380 9
                $options['aria-labelledby'] = $headerOptions['id'];
381
            }
382
383 9
            $encodeLabel = $item['encode'] ?? $this->encodeLabels;
384
385 9
            if ($encodeLabel) {
386 9
                $header = Html::encode($header);
387
            }
388
389 9
            $itemToggleOptions = array_merge([
390 9
                'tag' => 'button',
391 9
                'type' => 'button',
392 9
                'data-bs-toggle' => 'collapse',
393 9
                'data-bs-target' => '#' . $options['id'],
394 9
                'aria-expanded' => $expand ? 'true' : 'false',
395 9
                'aria-controls' => $options['id'],
396 9
            ], ArrayHelper::remove($item, 'toggleOptions', $this->itemToggleOptions));
397
398 9
            $itemToggleTag = ArrayHelper::remove($itemToggleOptions, 'tag', 'button');
399
400 9
            if ($itemToggleTag === 'a') {
401 1
                ArrayHelper::remove($itemToggleOptions, 'data-bs-target');
402 1
                $header = Html::a($header, '#' . $options['id'], $itemToggleOptions)->encode($this->encodeTags) . "\n";
403
            } else {
404 8
                Html::addCssClass($itemToggleOptions, ['widget' => 'accordion-button']);
405 8
                if (!$expand) {
406 7
                    Html::addCssClass($itemToggleOptions, ['expand' => 'collapsed']);
407
                }
408 8
                $header = Html::button($header, $itemToggleOptions)->encode($this->encodeTags)->render();
409
            }
410
411 9
            if (is_string($item['content']) || is_numeric($item['content']) || is_object($item['content'])) {
412 8
                $content = $item['content'];
413 3
            } elseif (is_array($item['content'])) {
414 2
                $items = [];
415 2
                foreach ($item['content'] as $content) {
416 2
                    $items[] = Html::div($content)
417 2
                        ->attributes(['class' => 'accordion-body'])
418 2
                        ->encode($this->encodeTags)
419 2
                        ->render();
420
                }
421
422 2
                $content = implode("\n", $items);
423
            } else {
424 9
                throw new RuntimeException('The "content" option should be a string, array or object.');
425
            }
426
        } else {
427 1
            throw new RuntimeException('The "content" option is required.');
428
        }
429
430 8
        if ($this->autoCloseItems) {
431 8
            $options['data-bs-parent'] = '#' . $this->getId();
432
        }
433
434 8
        $headerTag = ArrayHelper::remove($headerOptions, 'tag', 'h2');
435 8
        $group = Html::tag($headerTag, $header, $headerOptions)->encode($this->encodeTags) . "\n";
436 8
        $group .= Html::div($content, $options)->encode($this->encodeTags);
437
438 8
        return $group;
439
    }
440
}
441