SwiperSlider   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 293
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 8
dl 0
loc 293
ccs 86
cts 86
cp 1
rs 10
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A getHtmlElem() 0 6 1
A mergeGlobalStyles() 0 8 2
A run() 0 6 1
A registerAssets() 0 9 2
A registerPluginJs() 0 12 1
A getItemCssClass() 0 6 2
A init() 0 19 3
B makeHtml() 0 67 6
1
<?php
2
/**
3
 * Created on Tue Oct 27 2020.
4
 *
5
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
6
 * @copyright Copyright (c) 2010 - 2020 Sergey Coderius
7
 * @author Sergey Coderius <[email protected]>
8
 *
9
 * @see https://github.com/coderius - My github. See more my packages here...
10
 * @see https://coderius.biz.ua/ - My dev. blog
11
 *
12
 * Contact email: [email protected] - Have suggestions, contact me |:=)
13
 */
14
15
namespace coderius\swiperslider;
16
17
use yii\base\InvalidConfigException;
18
use yii\base\Widget;
19
use yii\helpers\ArrayHelper;
20
use yii\helpers\Html;
21
use yii\helpers\Json;
22
23
class SwiperSlider extends Widget
24
{
25
    const EVENT_BEFORE_REGISTER_DEFAULT_ASSET = 'beforeRegisterDefaultAsset';
26
    const EVENT_AFTER_REGISTER_DEFAULT_ASSET = 'afterRegisterDefaultAsset';
27
28
    const WIDGET_NAME = 'swiper';
29
    const JS_PLUGIN_NAME = 'Swiper';
30
31
    const CONTAINER = 'container';
32
    const WRAPPER = 'wrapper';
33
    const SLIDE = 'slide';
34
    const PAGINATION = 'pagination';
35
    const BUTTON_PREV = 'button-prev';
36
    const BUTTON_NEXT = 'button-next';
37
    const SCROLLBAR = 'scrollbar';
38
39
    const ASSET_DEFAULT = 'coderius\swiperslider\SwiperSliderAsset';
40
41
    /**
42
     * Cdn base url.
43
     *
44
     * @var string
45
     */
46
    const CDN_BASE_URL = 'https://unpkg.com/swiper';
47
48
    /**
49
     * Generate css class name for item.
50
     *
51
     * @param string $itemName
52
     * @param bool   $prefix
53
     *
54
     * @return string
55
     */
56 9
    public static function getItemCssClass($itemName, $prefix = true)
57
    {
58 9
        $prefix = $prefix ? '.' : '';
59
60 9
        return $prefix.self::WIDGET_NAME.'-'.$itemName;
61 1
    }
62
63
    /**
64
     * Widget options like inline styles etc.
65
     *
66
     * @var array
67
     */
68
    public $options = [];
69
70
    /**
71
     * If we need pagination.
72
     *
73
     * @var boolean
74
     */
75
    public $showPagination = true;
76
77
    /**
78
     * If we need scrollbar.
79
     *
80
     * @var boolean
81
     */
82
    public $showScrollbar = false;
83
84
    /**
85
     * Options in js plugin instance.
86
     *
87
     * @var array
88
     */
89
    public $clientOptions = [];
90
91
    /**
92
     * Default options for js plugin.
93
     *
94
     * @var array
95
     */
96
    public $defaultClientOptions = [];
97
98
    /**
99
     * If is allowed cdn base url to assets.
100
     *
101
     * @var boolean
102
     */
103
    public $assetFromCdn = false;
104
105
    /**
106
     * Sliders.
107
     *
108
     * @var array
109
     */
110
    public $slides = [];
111
112
    /**
113
     * Uniq widget name.
114
     *
115
     * @var string
116
     */
117
    protected $widgetId;
118
119
    protected $slideClass = "coderius\swiperslider\SlideDefault";
120
121
    /**
122
     * {@inheritdoc}
123
     */
124 9
    public function init()
125
    {
126 9
        parent::init();
127
128 9
        $this->defaultClientOptions = [
129 9
            'loop' => true,
130 9
            'pagination' => ['el' => static::getItemCssClass(static::PAGINATION)],
131
            'navigation' => [
132 9
                    'nextEl' => static::getItemCssClass(static::BUTTON_NEXT),
133 9
                    'prevEl' => static::getItemCssClass(static::BUTTON_PREV),
134 3
            ],
135
        ];
136
137 9
        $this->widgetId = $this->getId().'-'.static::WIDGET_NAME;
138
139 9
        if ($this->slides === null || empty($this->slides)) {
140 3
            throw new InvalidConfigException("The 'slides' option is required");
141
        }
142 6
    }
143
144
    /**
145
     * {@inheritdoc}
146
     */
147 6
    public function run()
148
    {
149 6
        $this->registerAssets();
150 6
        $this->registerPluginJs();
151 6
        echo $this->makeHtml();
152 6
    }
153
154
    /**
155
     * Processed registration all needed assets to widget
156
     * We can register custom asset by CustomAsset::register($view) by event hendler in widget options
157
     * echo SwiperSlider::widget([
158
     *      'on ' . SwiperSlider::EVENT_AFTER_REGISTER_DEFAULT_ASSET => function(){
159
     *                  CustomAsset::register($view)
160
     *       },
161
     *  ...
162
     *  ]);.
163
     *
164
     * @return void
165
     */
166 6
    protected function registerAssets()
167
    {
168 6
        $view = $this->getView();
169 6
        $this->trigger(self::EVENT_BEFORE_REGISTER_DEFAULT_ASSET);
170 6
        $dafaultAsset = static::ASSET_DEFAULT;
171 6
        $bundle = $dafaultAsset::register($view);
172 6
        false === $this->assetFromCdn ?: $bundle->fromCdn(static::CDN_BASE_URL);
173 6
        $this->trigger(self::EVENT_AFTER_REGISTER_DEFAULT_ASSET);
174 6
    }
175
176
    /**
177
     * Create html elements for widget.
178
     *
179
     * @return void
180
     */
181 6
    protected function makeHtml()
182
    {
183
        //Slides
184
        //S
185 6
        $slides = [];
186 6
        $index = 0;
187 6
        foreach ($this->slides as $slide) {
188 6
            if (is_string($slide)) {
189 6
                $htmlSlide = $this->getHtmlElem(static::SLIDE, [], $slide);
190 2
            } else {
191
                //Mergin current slide attributes with global widget options styles pasted to all elements on this type
192
                //Example in widget init options -  `SwiperSlider::SLIDE => ["text-align" => "center"]`
193 3
                $slide['options'] = $this->mergeGlobalStyles(static::SLIDE, $slide['options']);
194 3
                $inctanseSlide = \Yii::createObject(array_merge([
195 3
                    'class' => $this->slideClass ?: SlideDefault::class,
196 3
                    'slider' => $this,
197 3
                ], $slide));
198
                //Invoke function in instance SlideDefault::renderSlideHtml
199 3
                $htmlSlide = $inctanseSlide->renderSlideHtml('div', $index);
200
            }
201
202 6
            $slides[] = $htmlSlide;
203 6
            ++$index;
204 2
        }
205 6
        $slides = "\n".implode("\n", $slides)."\n";
206
207
        //Slides wrapper
208 6
        $wrapper = $this->getHtmlElem(static::WRAPPER, [], $slides);
209
210
        //Pagination
211 6
        $pagination = $this->getHtmlElem(static::PAGINATION);
212
213
        //Navigation buttons
214 6
        $buttonPrev = $this->getHtmlElem(static::BUTTON_PREV);
215 6
        $buttonNext = $this->getHtmlElem(static::BUTTON_NEXT);
216
217
        //Scrollbar
218 6
        $scrollbar = $this->getHtmlElem(static::SCROLLBAR);
219
220
        //Collect all content
221 6
        $content = [];
222 6
        $content[] = $wrapper;
223
224
        // And if we need pagination
225 6
        if ($this->showPagination) {
226 6
            $content[] = $pagination;
227 2
        }
228
229 6
        $content[] = $buttonPrev;
230 6
        $content[] = $buttonNext;
231
232
        // And if we need scrollbar
233 6
        if ($this->showScrollbar) {
234 3
            $content[] = $scrollbar;
235 1
        }
236
237 6
        $content = "\n".implode("\n", $content)."\n";
238
239
        //Common container
240 6
        $container = "\n";
241 6
        $container .= "<!-- ***Swiper slider widget id: {$this->widgetId}*** -->";
242 6
        $container .= "\n";
243 6
        $container .= $this->getHtmlElem(static::CONTAINER, ['id' => $this->widgetId], $content);
244 6
        $container .= "\n<!-- ///Swiper slider widget id: {$this->widgetId}/// -->";
245
246 6
        return  $container;
247
    }
248
249
    /**
250
     * getHtmlElem function help create html element and add custom inline css styles.
251
     *
252
     * @param string $itemName
253
     * @param array  $options
254
     * @param string $content
255
     * @param string $tag
256
     *
257
     * @return string
258
     */
259 6
    protected function getHtmlElem($itemName, $options = [], $content = '', $tag = 'div')
260
    {
261 6
        $options = $this->mergeGlobalStyles($itemName, $options);
262
263 6
        return Html::tag($tag, $content, $options);
264
    }
265
266
    /**
267
     * Merge options array with default params like `class` and global options pasted when widget created
268
     * Example:
269
     * echo SwiperSlider::widget([
270
     * ...
271
     * 'options' => [
272
     *      'styles' => [
273
     *          SwiperSlider::CONTAINER => ["height" => "100px"],
274
     *          SwiperSlider::SLIDE => ["text-align" => "center"],
275
     *      ],
276
     *      'show-scrollbar' => true,
277
     *  ],
278
     * ...
279
     * ]);.
280
     *
281
     * In this example we merge options for html elements `container`  and  `slide` and default created options `class` for them getted
282
     * by function static::getItemCssClass($itemName, false)
283
     *
284
     * @param string $itemName
285
     * @param [type] $options
0 ignored issues
show
Documentation introduced by
The doc-type [type] could not be parsed: Unknown type name "" at position 0. [(view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
286
     *
287
     * @return void
288
     */
289 6
    protected function mergeGlobalStyles($itemName, $options)
290
    {
291 6
        $options = ArrayHelper::merge(['class' => static::getItemCssClass($itemName, false)], $options);
292 6
        $style = !empty($this->options['styles'][$itemName]) ? $this->options['styles'][$itemName] : null;
293 6
        Html::addCssStyle($options, $style);
294
295 6
        return $options;
296
    }
297
298
    /**
299
     * registerPluginJs function.
300
     *
301
     * @return void
302
     */
303 6
    protected function registerPluginJs()
304
    {
305 6
        $view = $this->getView();
306 6
        $pluginParams = [];
307 6
        $pluginParams[] = JsHelper::addString('#'.$this->widgetId);
308 6
        $clientOptions = ArrayHelper::merge($this->defaultClientOptions, $this->clientOptions);
309 6
        $pluginParams[] = Json::encode($clientOptions);
310 6
        $pluginInstance = JsHelper::newJsObject(static::JS_PLUGIN_NAME, $pluginParams);
311 6
        $jsVar = JsHelper::initVar('mySwiper', $pluginInstance);
312
313 6
        $view->registerJs($jsVar, \yii\web\View::POS_END);
314 6
    }
315
}
316