Passed
Push — master ( 34e66c...44dbec )
by Sergei
03:09
created

Accordion::defaultExpand()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3.0261

Importance

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

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

396
            ->/** @scrutinizer ignore-call */ withToggleLabel($item['label'])
Loading history...
397 13
            ->withToggleOptions($toggleOptions)
398 13
            ->withOptions($options)
399 13
            ->withContent($this->renderBody($item))
400 13
            ->withBodyOptions($bodyOptions)
401 13
            ->withCollapsed($expand)
402 13
            ->withToggle(false);
403
    }
404
405
    /**
406
     * Render collapse body
407
     */
408 13
    private function renderBody(array $item): string
409
    {
410 13
        $items = '';
411
412 13
        if ($this->isStringableObject($item['content'])) {
413 1
            $content = [$item['content']];
414
        } else {
415 13
            $content = (array) $item['content'];
416
        }
417
418 13
        foreach ($content as $value) {
419 13
            if (!is_string($value) && !is_numeric($value) && !$this->isStringableObject($value)) {
420 1
                throw new RuntimeException('The "content" option should be a string, array or object.');
421
            }
422
423 12
            $items .= $value;
424
        }
425
426 12
        return $items;
427
    }
428
429 13
    private function isStringableObject(mixed $value): bool
430
    {
431 13
        return $value instanceof Stringable;
432
    }
433
}
434