Test Failed
Pull Request — master (#35)
by Wilmer
03:25 queued 01:10
created

Carousel::renderItem()   B

Complexity

Conditions 7
Paths 17

Size

Total Lines 37
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 22
c 1
b 0
f 0
nc 17
nop 2
dl 0
loc 37
ccs 0
cts 6
cp 0
crap 56
rs 8.6346
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 count;
13
use function implode;
14
use function is_string;
15
16
/**
17
 * Carousel renders a carousel bootstrap javascript component.
18
 *
19
 * For example:
20
 *
21
 * ```php
22
 * echo Carousel::widget()
23
 *     ->withItems([
24
 *         // the item contains only the image
25
 *         '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-01.jpg"/>',
26
 *         // equivalent to the above
27
 *         ['content' => '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-02.jpg"/>'],
28
 *         // the item contains both the image and the caption
29
 *         [
30
 *             'content' => '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-03.jpg"/>',
31
 *             'caption' => '<h4>This is title</h4><p>This is the caption text</p>',
32
 *             'captionOptions' => ['class' => ['d-none', 'd-md-block']],
33
 *             'options' => [...],
34
 *         ],
35
 *     ]);
36
 * ```
37
 */
38
final class Carousel extends Widget
39
{
40
    private array $controls = [
41
        '<span class="carousel-control-prev-icon" aria-hidden="true"></span><span class="visually-hidden">Previous</span>',
42
        '<span class="carousel-control-next-icon" aria-hidden="true"></span><span class="visually-hidden">Next</span>',
43
    ];
44
    private bool $encodeTags = false;
45
    private bool $showIndicators = true;
46
    private array $items = [];
47
    private bool $crossfade = false;
48
    private array $options = ['data-bs-ride' => 'carousel'];
49 2
50
    public function run(): string
51 2
    {
52 2
        if (!isset($this->options['id'])) {
53
            $this->options['id'] = "{$this->getId()}-carousel";
54
        }
55
56 2
        /** @psalm-suppress InvalidArgument */
57
        Html::addCssClass($this->options, ['widget' => 'carousel', 'slide']);
58 2
59 1
        if ($this->crossfade) {
60
            Html::addCssClass($this->options, 'carousel-fade');
61
        }
62 2
63
        if ($this->encodeTags === false) {
64 2
            $this->options = array_merge($this->options, ['encode' => false]);
65 2
        }
66 2
67
        return Html::div(
68
            $this->renderIndicators() . $this->renderItems() . $this->renderControls(),
69
            $this->options
70
        );
71
    }
72
73 2
    /**
74
     * The labels for the previous and the next control buttons.
75 2
     *
76
     * If null, it means the previous and the next control buttons should not be displayed.
77
     *
78
     * @param array|null $value
79 2
     *
80
     * @return $this
81 2
     */
82 2
    public function withControls(array $value): self
83 2
    {
84
        $new = clone $this;
85 2
        $new->controls = $value;
86
87 2
        return $new;
88
    }
89
90 2
    /**
91
     * Animate slides with a fade transition instead of a slide. Defaults to `false`.
92
     *
93
     * @param bool $value
94
     *
95
     * @return $this
96 2
     */
97
    public function withCrossfade(bool $value): self
98 2
    {
99
        $new = clone $this;
100 2
        $new->crossfade = $value;
101 2
102
        return $new;
103
    }
104 2
105
    /**
106
     * List of slides in the carousel. Each array element represents a single slide with the following structure:
107
     *
108
     * ```php
109
     * [
110
     *     // required, slide content (HTML), such as an image tag
111
     *     'content' => '<img src="http://twitter.github.io/bootstrap/assets/img/bootstrap-mdo-sfmoma-01.jpg"/>',
112
     *     // optional, the caption (HTML) of the slide
113
     *     'caption' => '<h4>This is title</h4><p>This is the caption text</p>',
114
     *     // optional the HTML attributes of the slide container
115
     *     'options' => [],
116
     * ]
117 2
     * ```
118
     *
119 2
     * @param array $value
120
     *
121
     * @return $this
122
     */
123 2
    public function withItems(array $value): self
124 2
    {
125 2
        $new = clone $this;
126
        $new->items = $value;
127 2
128 2
        return $new;
129 2
    }
130
131 2
    /**
132
     * The HTML attributes for the container tag. The following special options are recognized.
133
     *
134 2
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
135
     *
136
     * @param array $value
137
     *
138
     * @return $this
139 2
     */
140
    public function withOptions(array $value): self
141 2
    {
142 2
        $new = clone $this;
143
        $new->options = $value;
144
145 2
        return $new;
146
    }
147
148
    /**
149
     * Whether carousel indicators (<ol> tag with anchors to items) should be displayed or not.
150
     *
151
     * @param bool $value
152
     *
153
     * @return $this
154
     */
155 2
    public function withoutShowIndicators(bool $value = false): self
156
    {
157 2
        $new = clone $this;
158 2
        $new->showIndicators = $value;
159 2
160
        return $new;
161
    }
162 2
163 2
    /**
164 2
     * Allows you to enable or disable the encoding tags html.
165
     *
166
     * @param bool $value
167
     *
168
     * @return self
169
     */
170
    public function withEncodeTags(bool $value = true): self
171
    {
172
        $new = clone $this;
173
        $new->encodeTags = $value;
174
175
        return $new;
176
    }
177
178
    /**
179
     * Renders carousel indicators.
180
     */
181
    private function renderIndicators(): string
182
    {
183
        if ($this->showIndicators === false) {
184
            return '';
185
        }
186
187
        $indicators = [];
188
189
        for ($i = 0, $count = count($this->items); $i < $count; $i++) {
190
            $options = ['data-bs-target' => '#' . $this->options['id'], 'data-bs-slide-to' => $i];
191
            if ($i === 0) {
192
                /** @psalm-suppress InvalidArgument */
193
                Html::addCssClass($options, 'active');
194
            }
195
            $indicators[] = Html::tag('li', '', $options);
196
        }
197
198
        $indicatorOptions = ['class' => ['carousel-indicators']];
199
200
        if ($this->encodeTags === false) {
201
            $indicatorOptions = array_merge($indicatorOptions, ['encode' => false]);
202 1
        }
203
204 1
        return Html::tag('ol', implode("\n", $indicators), $indicatorOptions);
205
    }
206 1
207
    /**
208
     * Renders carousel items as specified on {@see items}.
209
     */
210
    private function renderItems(): string
211
    {
212
        $items = [];
213
214
        foreach ($this->items as $i => $iValue) {
215
            $items[] = $this->renderItem($iValue, $i);
216
        }
217
218
        $itemOptions = ['class' => 'carousel-inner'];
219
220
        if ($this->encodeTags === false) {
221
            $itemOptions = array_merge($itemOptions, ['encode' => false]);
222
        }
223
224
        return Html::div(implode("\n", $items), $itemOptions);
225
    }
226
227 2
    /**
228
     * Renders a single carousel item
229 2
     *
230
     * @param array|string $item a single item from {@see items}
231 2
     * @param int $index the item index as the first item should be set to `active`
232
     *
233
     * @throws JsonException|RuntimeException if the item is invalid.
234
     *
235
     * @return string the rendering result.
236
     */
237
    private function renderItem($item, int $index): string
238
    {
239
        if (is_string($item)) {
240
            $content = $item;
241
            $caption = null;
242
            $options = [];
243
        } elseif (isset($item['content'])) {
244
            $content = $item['content'];
245
            $caption = ArrayHelper::getValue($item, 'caption');
246
247
            if ($caption !== null) {
248
                $captionOptions = ArrayHelper::remove($item, 'captionOptions', []);
249
                Html::addCssClass($captionOptions, ['widget' => 'carousel-caption']);
250
251
                if ($this->encodeTags === false) {
252
                    $captionOptions = array_merge($captionOptions, ['encode' => false]);
253
                }
254
255
                $caption = Html::div($caption, $captionOptions);
256
            }
257
258
            $options = ArrayHelper::getValue($item, 'options', []);
259
        } else {
260
            throw new RuntimeException('The "content" option is required.');
261
        }
262
263
        Html::addCssClass($options, ['widget' => 'carousel-item']);
264
265
        if ($this->encodeTags === false) {
266
            $options = array_merge($options, ['encode' => false]);
267
        }
268
269
        if ($index === 0) {
270
            Html::addCssClass($options, 'active');
271
        }
272
273
        return Html::div($content . "\n" . $caption, $options);
274
    }
275
276
    /**
277
     * Renders previous and next control buttons.
278
     *
279
     * @throws JsonException|RuntimeException if {@see controls} is invalid.
280
     *
281
     * @return string
282
     */
283
    private function renderControls(): string
284
    {
285
        $controlsOptions0 = [
286
            'class' => 'carousel-control-prev',
287
            'data-bs-slide' => 'prev',
288
            'role' => 'button',
289
        ];
290
291
        $controlsOptions1 = [
292
            'class' => 'carousel-control-next',
293
            'data-bs-slide' => 'next',
294
            'role' => 'button',
295
        ];
296
297
        if ($this->encodeTags === false) {
298
            $controlsOptions0 = array_merge($controlsOptions0, ['encode' => false]);
299
            $controlsOptions1 = array_merge($controlsOptions1, ['encode' => false]);
300
        }
301
302
        if (isset($this->controls[0], $this->controls[1])) {
303
            return Html::a($this->controls[0], '#' . $this->options['id'], $controlsOptions0) . "\n" .
304
                Html::a($this->controls[1], '#' . $this->options['id'], $controlsOptions1);
305
        }
306
307
        if ($this->controls === []) {
308
            return '';
309
        }
310
311
        throw new RuntimeException(
312
            'The "controls" property must be either null or an array of two elements.'
313
        );
314
    }
315
}
316