Passed
Pull Request — master (#35)
by Wilmer
02:31
created

Carousel::withOptions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 1
rs 10
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
50 9
    protected function run(): string
51
    {
52 9
        if (!isset($this->options['id'])) {
53 9
            $this->options['id'] = "{$this->getId()}-carousel";
54
        }
55
56
        /** @psalm-suppress InvalidArgument */
57 9
        Html::addCssClass($this->options, ['widget' => 'carousel', 'slide']);
58
59 9
        if ($this->crossfade) {
60 1
            Html::addCssClass($this->options, ['crossfade' => 'carousel-fade']);
61
        }
62
63 9
        if ($this->encodeTags === false) {
64 8
            $this->options = array_merge($this->options, ['encode' => false]);
65
        }
66
67 9
        return Html::div(
68 9
            $this->renderIndicators() . $this->renderItems() . $this->renderControls(),
69 7
            $this->options
70
        );
71
    }
72
73
    /**
74
     * The labels for the previous and the next control buttons.
75
     *
76
     * If null, it means the previous and the next control buttons should not be displayed.
77
     *
78
     * @param array $value
79
     *
80
     * @return $this
81
     */
82 2
    public function withControls(array $value): self
83
    {
84 2
        $new = clone $this;
85 2
        $new->controls = $value;
86
87 2
        return $new;
88
    }
89
90
    /**
91
     * Animate slides with a fade transition instead of a slide. Defaults to `false`.
92
     *
93
     * @param bool $value
94
     *
95
     * @return $this
96
     */
97 1
    public function withCrossfade(bool $value): self
98
    {
99 1
        $new = clone $this;
100 1
        $new->crossfade = $value;
101
102 1
        return $new;
103
    }
104
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
     * ```
118
     *
119
     * @param array $value
120
     *
121
     * @return $this
122
     */
123 9
    public function withItems(array $value): self
124
    {
125 9
        $new = clone $this;
126 9
        $new->items = $value;
127
128 9
        return $new;
129
    }
130
131
    /**
132
     * The HTML attributes for the container tag. The following special options are recognized.
133
     *
134
     * {@see Html::renderTagAttributes()} for details on how attributes are being rendered.
135
     *
136
     * @param array $value
137
     *
138
     * @return $this
139
     */
140 1
    public function withOptions(array $value): self
141
    {
142 1
        $new = clone $this;
143 1
        $new->options = $value;
144
145 1
        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 1
    public function withoutShowIndicators(bool $value = false): self
156
    {
157 1
        $new = clone $this;
158 1
        $new->showIndicators = $value;
159
160 1
        return $new;
161
    }
162
163
    /**
164
     * Allows you to enable or disable the encoding tags html.
165
     *
166
     * @param bool $value
167
     *
168
     * @return self
169
     */
170 1
    public function withEncodeTags(bool $value = true): self
171
    {
172 1
        $new = clone $this;
173 1
        $new->encodeTags = $value;
174
175 1
        return $new;
176
    }
177
178
    /**
179
     * Renders carousel indicators.
180
     */
181 9
    private function renderIndicators(): string
182
    {
183 9
        if ($this->showIndicators === false) {
184 1
            return '';
185
        }
186
187 8
        $indicators = [];
188
189 8
        for ($i = 0, $count = count($this->items); $i < $count; $i++) {
190 8
            $options = ['data-bs-target' => '#' . $this->options['id'], 'data-bs-slide-to' => $i];
191 8
            if ($i === 0) {
192
                /** @psalm-suppress InvalidArgument */
193 8
                Html::addCssClass($options, ['active' => 'active']);
194
            }
195 8
            $indicators[] = Html::tag('li', '', $options);
196
        }
197
198 8
        $indicatorOptions = ['class' => ['carousel-indicators']];
199
200 8
        if ($this->encodeTags === false) {
201 7
            $indicatorOptions = array_merge($indicatorOptions, ['encode' => false]);
202
        }
203
204 8
        return Html::tag('ol', implode("\n", $indicators), $indicatorOptions);
205
    }
206
207
    /**
208
     * Renders carousel items as specified on {@see items}.
209
     */
210 9
    private function renderItems(): string
211
    {
212 9
        $items = [];
213
214 9
        foreach ($this->items as $i => $iValue) {
215 9
            $items[] = $this->renderItem($iValue, $i);
216
        }
217
218 8
        $itemOptions = ['class' => 'carousel-inner'];
219
220 8
        if ($this->encodeTags === false) {
221 7
            $itemOptions = array_merge($itemOptions, ['encode' => false]);
222
        }
223
224 8
        return Html::div(implode("\n", $items), $itemOptions);
225
    }
226
227
    /**
228
     * Renders a single carousel item
229
     *
230
     * @param array|string $item a single item from {@see items}
231
     * @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 9
    private function renderItem($item, int $index): string
238
    {
239 9
        if (is_string($item)) {
240 1
            $content = $item;
241 1
            $caption = null;
242 1
            $options = [];
243 8
        } elseif (isset($item['content'])) {
244 7
            $content = $item['content'];
245 7
            $caption = ArrayHelper::getValue($item, 'caption');
246
247 7
            if ($caption !== null) {
248 7
                $captionOptions = ArrayHelper::remove($item, 'captionOptions', []);
249 7
                Html::addCssClass($captionOptions, ['captionOptions' => 'carousel-caption']);
250
251 7
                if ($this->encodeTags === false) {
252 6
                    $captionOptions = array_merge($captionOptions, ['encode' => false]);
253
                }
254
255 7
                $caption = Html::div($caption, $captionOptions);
256
            }
257
258 7
            $options = ArrayHelper::getValue($item, 'options', []);
259
        } else {
260 1
            throw new RuntimeException('The "content" option is required.');
261
        }
262
263 8
        Html::addCssClass($options, ['widget' => 'carousel-item']);
264
265 8
        if ($this->encodeTags === false) {
266 7
            $options = array_merge($options, ['encode' => false]);
267
        }
268
269 8
        if ($index === 0) {
270 8
            Html::addCssClass($options, ['active' => 'active']);
271
        }
272
273 8
        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 8
    private function renderControls(): string
284
    {
285
        $controlsOptions0 = [
286 8
            'class' => 'carousel-control-prev',
287
            'data-bs-slide' => 'prev',
288
            'role' => 'button',
289
        ];
290
291
        $controlsOptions1 = [
292 8
            'class' => 'carousel-control-next',
293
            'data-bs-slide' => 'next',
294
            'role' => 'button',
295
        ];
296
297 8
        if ($this->encodeTags === false) {
298 7
            $controlsOptions0 = array_merge($controlsOptions0, ['encode' => false]);
299 7
            $controlsOptions1 = array_merge($controlsOptions1, ['encode' => false]);
300
        }
301
302 8
        if (isset($this->controls[0], $this->controls[1])) {
303 6
            return Html::a($this->controls[0], '#' . $this->options['id'], $controlsOptions0) . "\n" .
304 6
                Html::a($this->controls[1], '#' . $this->options['id'], $controlsOptions1);
305
        }
306
307 2
        if ($this->controls === []) {
308 1
            return '';
309
        }
310
311 1
        throw new RuntimeException(
312 1
            'The "controls" property must be either null or an array of two elements.'
313
        );
314
    }
315
}
316