Completed
Push — master ( b786a3...732fc9 )
by Klochok
04:59
created

IndexPage::horizontalClientScriptInit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 58
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 58
ccs 0
cts 57
cp 0
crap 2
rs 9.639
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/*
4
 * HiPanel core package
5
 *
6
 * @link      https://hipanel.com/
7
 * @package   hipanel-core
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2014-2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\widgets;
13
14
use Yii;
15
use yii\base\InvalidParamException;
16
use yii\base\Model;
17
use yii\base\Widget;
18
use yii\bootstrap\ButtonDropdown;
19
use yii\data\DataProviderInterface;
20
use yii\helpers\Html;
21
use yii\helpers\Inflector;
22
use yii\helpers\Json;
23
use yii\helpers\Url;
24
use yii\web\View;
25
26
class IndexPage extends Widget
27
{
28
29
    /**
30
     * @var string
31
     */
32
    protected $_layout;
33
34
    /**
35
     * @var Model the search model
36
     */
37
    public $model;
38
39
    /**
40
     * @var object original view context.
41
     * It is used to render sub-views with the same context, as IndexPage
42
     */
43
    public $originalContext;
44
45
    /**
46
     * @var DataProviderInterface
47
     */
48
    public $dataProvider;
49
50
    /**
51
     * @var array Hash of document blocks, that can be rendered later in the widget's views
52
     * Blocks can be set explicitly on widget initialisation, or by calling [[beginContent]] and
53
     * [[endContent]]
54
     *
55
     * @see beginContent
56
     * @see endContent
57
     */
58
    public $contents = [];
59
60
    /**
61
     * @var string the name of current content block, that is under the render
62
     * @see beginContent
63
     * @see endContent
64
     */
65
    protected $_current = null;
66
67
    /**
68
     * @var array
69
     */
70
    public $searchFormData = [];
71
72
    /**
73
     * @var array
74
     */
75
    public $searchFormOptions = [];
76
77
    /**
78
     * @var string the name of view file that contains search fields for the index page. Defaults to `_search`
79
     * @see renderSearchForm()
80
     */
81
    public $searchView = '_search';
82
83
    /** {@inheritdoc} */
84
    public function init()
85
    {
86
        parent::init();
87
        $searchFormId = Json::htmlEncode("#{$this->getBulkFormId()}");
88
        $this->originalContext = Yii::$app->view->context;
89
        $view = $this->getView();
90
        $view->registerJs(<<<JS
91
        // Checkbox
92
        var checkboxes = $('table input[type="checkbox"]');
93
        var bulkcontainer = $('.box-bulk-actions fieldset');
94
        checkboxes.on('ifChecked ifUnchecked', function(event) {
95
            if (event.type == 'ifChecked' && $('input.icheck').filter(':checked').length > 0) {
96
                bulkcontainer.prop('disabled', false);
97
            } else if ($('input.icheck').filter(':checked').length == 0) {
98
                bulkcontainer.prop('disabled', true);
99
            }
100
        });
101
        // On/Off Actions TODO: reduce scope
102
        $(document).on('click', '.box-bulk-actions a', function (event) {
103
            var link = $(this);
104
            var action = link.data('action');
105
            var form = $($searchFormId);
106
            if (action) {
107
                form.attr({'action': action, method: 'POST'}).submit();
108
            }
109
        });
110
JS
111
        );
112
    }
113
114
    /**
115
     * Begins output buffer capture to save data in [[contents]] with the $name key.
116
     * Must not be called nested. See [[endContent]] for capture terminating.
117
     * @param string $name
118
     */
119
    public function beginContent($name)
120
    {
121
        if ($this->_current) {
122
            throw new InvalidParamException('Output buffer capture is already running for ' . $this->_current);
123
        }
124
        $this->_current = $name;
125
        ob_start();
126
        ob_implicit_flush(false);
127
    }
128
129
    /**
130
     * Terminates output buffer capture started by [[beginContent()]].
131
     * @see beginContent
132
     */
133
    public function endContent()
134
    {
135
        if (!$this->_current) {
136
            throw new InvalidParamException('Outout buffer capture is not running. Call beginContent() first');
137
        }
138
        $this->contents[$this->_current] = ob_get_contents();
139
        ob_end_clean();
140
        $this->_current = null;
141
    }
142
143
    /**
144
     * Returns content saved in [[content]] by $name.
145
     * @param string $name
146
     * @return string
147
     */
148
    public function renderContent($name)
149
    {
150
        return $this->contents[$name];
151
    }
152
153
    public function run()
154
    {
155
        $layout = $this->getLayout();
156
        if ($layout === 'horizontal') {
157
            $this->horizontalClientScriptInit();
158
        }
159
160
        return $this->render($layout);
161
    }
162
163
    private function horizontalClientScriptInit()
164
    {
165
        $view = $this->getView();
166
        $view->registerCss('
167
            .affix {
168
                top: 5px;
169
            }
170
            .affix-bottom {
171
                position: fixed!important;
172
            }
173
            @media (min-width: 768px) {
174
                .affix {
175
                    position: fixed;
176
                }
177
            }
178
            @media (max-width: 768px) {
179
                .affix {
180
                    position: static;
181
                }
182
            }
183
            .advanced-search[min-width~="150px"] form > div {
184
                width: 100%;
185
            }
186
        ');
187
        $view->registerJs("
188
            function affixInit() {
189
                $('#scrollspy').affix({
190
                    offset: {
191
                        top: ($('header.main-header').outerHeight(true) + $('section.content-header').outerHeight(true)) + 15,
192
                        bottom: ($('footer').outerHeight(true)) + 15
193
                    }
194
                });
195
            }
196
            $(document).on('pjax:end', function() {
197
                $('.advanced-search form > div').css({'width': '100%'});
198
                
199
                // Fix left search block position
200
                $(window).trigger('scroll');
201
            });
202
            if ($(window).height() > $('#scrollspy').outerHeight(true) && $(window).width() > 991) {
203
                if ( $('#scrollspy').outerHeight(true) < $('.horizontal-view .col-md-9 > .box').outerHeight(true) ) {
204
                    var fixAffixWidth = function() {
205
                        $('#scrollspy').each(function() {
206
                            $(this).width( $(this).parent().width() );
207
                        });
208
                    }
209
                    fixAffixWidth();
210
                    $(window).resize(fixAffixWidth);
211
                    affixInit();
212
                    $('a.sidebar-toggle').click(function() {
213
                        setTimeout(function(){
214
                            fixAffixWidth();
215
                        }, 500);
216
                    });
217
                }
218
            }
219
        ", View::POS_LOAD);
220
    }
221
222
    public function detectLayout()
223
    {
224
        $os = Yii::$app->get('orientationStorage');
225
        $n = $os->get(Yii::$app->controller->getRoute());
226
        return $n;
227
    }
228
229
    public function setSearchFormData($data = [])
230
    {
231
        $this->searchFormData = $data;
232
    }
233
234
    public function setSearchFormOptions($options = [])
235
    {
236
        $this->searchFormOptions = $options;
237
    }
238
239
    public function renderSearchForm($advancedSearchOptions = [])
240
    {
241
        $advancedSearchOptions = array_merge($advancedSearchOptions, $this->searchFormOptions);
242
        ob_start();
243
        ob_implicit_flush(false);
244
        try {
245
            $search = $this->beginSearchForm($advancedSearchOptions);
246
            foreach (['per_page', 'representation'] as $key) {
247
                echo Html::hiddenInput($key, Yii::$app->request->get($key));
248
            }
249
            echo Yii::$app->view->render($this->searchView, array_merge(compact('search'), $this->searchFormData), $this->originalContext);
250
            $search->end();
251
        } catch (\Exception $e) {
252
            ob_end_clean();
253
            throw $e;
254
        }
255
256
        return ob_get_clean();
257
    }
258
259
    public function beginSearchForm($options = [])
260
    {
261
        return AdvancedSearch::begin(array_merge(['model' => $this->model], $options));
262
    }
263
264
    public function renderSearchButton()
265
    {
266
        return AdvancedSearch::renderButton() . "\n";
267
    }
268
269
    public function renderLayoutSwitcher()
270
    {
271
        return IndexLayoutSwitcher::widget();
272
    }
273
274 View Code Duplication
    public function renderPerPage()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
275
    {
276
        return ButtonDropdown::widget([
277
            'label' => Yii::t('hipanel', 'Per page') . ': ' . (Yii::$app->request->get('per_page') ?: 25),
278
            'options' => ['class' => 'btn-default btn-sm'],
279
            'dropdown' => [
280
                'items' => [
281
                    ['label' => '25', 'url' => Url::current(['per_page' => null])],
282
                    ['label' => '50', 'url' => Url::current(['per_page' => 50])],
283
                    ['label' => '100', 'url' => Url::current(['per_page' => 100])],
284
                    ['label' => '200', 'url' => Url::current(['per_page' => 200])],
285
                    ['label' => '500', 'url' => Url::current(['per_page' => 500])],
286
                ],
287
            ],
288
        ]);
289
    }
290
291
    /**
292
     * Renders button to choose representation.
293
     * Returns empty string when nothing to choose (less then 2 representations available).
294
     * @param array $grid class
295
     * @param mixed $current selected representation
296
     * @return string rendered HTML
297
     */
298
    public static function renderRepresentations($grid, $current)
299
    {
300
        $representations = $grid::getRepresentations();
301
        if (count($representations) < 2) {
302
            return '';
303
        }
304
        if (!isset($representations[$current])) {
305
            $current = key($representations);
306
        }
307
        $items = [];
308
        foreach ($representations as $key => $data) {
309
            $items[] = [
310
                'label' => $data['label'],
311
                'url' => Url::current(['representation' => $key]),
312
            ];
313
        }
314
315
        return ButtonDropdown::widget([
316
            'label' => Yii::t('synt', 'View') . ': ' . $representations[$current]['label'],
317
            'options' => ['class' => 'btn-default btn-sm'],
318
            'dropdown' => [
319
                'items' => $items,
320
            ],
321
        ]);
322
    }
323
324 View Code Duplication
    public function renderSorter(array $options)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
325
    {
326
        return LinkSorter::widget(array_merge([
327
            'show' => true,
328
            'sort' => $this->dataProvider->getSort(),
329
            'buttonClass' => 'btn btn-default dropdown-toggle btn-sm',
330
        ], $options));
331
    }
332
333
    public function getViewPath()
334
    {
335
        return parent::getViewPath() . DIRECTORY_SEPARATOR . (new \ReflectionClass($this))->getShortName();
336
    }
337
338
    public function getBulkFormId()
339
    {
340
        return 'bulk-' . Inflector::camel2id($this->model->formName());
341
    }
342
343
    public function beginBulkForm($action = '')
344
    {
345
        echo Html::beginForm($action, 'POST', ['id' => $this->getBulkFormId()]);
346
    }
347
348
    public function endBulkForm()
349
    {
350
        echo Html::endForm();
351
    }
352
353 View Code Duplication
    public function renderBulkButton($text, $action, $color = 'default')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
354
    {
355
        return Html::submitButton($text, [
356
            'class' => "btn btn-$color btn-sm",
357
            'form' => $this->getBulkFormId(),
358
            'formmethod' => 'POST',
359
            'formaction' => $action,
360
        ]);
361
    }
362
363
    /**
364
     * @return string
365
     */
366
    public function getLayout()
367
    {
368
        if ($this->_layout === null) {
369
            $this->_layout = $this->detectLayout();
370
        }
371
        return $this->_layout;
372
    }
373
374
    /**
375
     * @param string $layout
376
     */
377
    public function setLayout($layout)
378
    {
379
        $this->_layout = $layout;
380
    }
381
}
382