Completed
Push — master ( 471d6c...1516ad )
by Andrii
12:30
created

IndexPage   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 292
Duplicated Lines 11.3 %

Coupling/Cohesion

Components 4
Dependencies 14

Test Coverage

Coverage 0%

Importance

Changes 8
Bugs 1 Features 3
Metric Value
dl 33
loc 292
ccs 0
cts 179
cp 0
rs 9.8
c 8
b 1
f 3
wmc 31
lcom 4
cbo 14

22 Methods

Rating   Name   Duplication   Size   Complexity  
A detectLayout() 0 6 1
A setSearchFormOptions() 0 4 1
A beginSearchForm() 0 4 1
A renderSearchButton() 0 4 1
A setSearchFormData() 0 4 1
A renderSearchForm() 0 19 3
A renderContent() 0 4 1
A run() 0 4 1
B init() 0 29 1
A beginContent() 0 9 2
A endContent() 0 9 2
A renderLayoutSwitcher() 0 4 1
A renderPerPage() 16 16 2
B renderRepresentations() 0 25 4
A renderSorter() 8 8 1
A getViewPath() 0 4 1
A getBulkFormId() 0 4 1
A beginBulkForm() 0 4 1
A endBulkForm() 0 4 1
A renderBulkButton() 9 9 1
A getLayout() 0 7 2
A setLayout() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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
25
class IndexPage extends Widget
26
{
27
28
    /**
29
     * @var string
30
     */
31
    protected $_layout;
32
33
    /**
34
     * @var Model the search model
35
     */
36
    public $model;
37
38
    /**
39
     * @var object original view context.
40
     * It is used to render sub-views with the same context, as IndexPage
41
     */
42
    public $originalContext;
43
44
    /**
45
     * @var DataProviderInterface
46
     */
47
    public $dataProvider;
48
49
    /**
50
     * @var array Hash of document blocks, that can be rendered later in the widget's views
51
     * Blocks can be set explicitly on widget initialisation, or by calling [[beginContent]] and
52
     * [[endContent]]
53
     *
54
     * @see beginContent
55
     * @see endContent
56
     */
57
    public $contents = [];
58
59
    /**
60
     * @var string the name of current content block, that is under the render
61
     * @see beginContent
62
     * @see endContent
63
     */
64
    protected $_current = null;
65
66
    /**
67
     * @var array
68
     */
69
    public $searchFormData = [];
70
71
    /**
72
     * @var array
73
     */
74
    public $searchFormOptions = [];
75
76
    /**
77
     * @var string the name of view file that contains search fields for the index page. Defaults to `_search`
78
     * @see renderSearchForm()
79
     */
80
    public $searchView = '_search';
81
82
    /** {@inheritdoc} */
83
    public function init()
84
    {
85
        parent::init();
86
        $searchFormId = Json::htmlEncode("#{$this->getBulkFormId()}");
87
        $this->originalContext = Yii::$app->view->context;
88
        $view = $this->getView();
89
        $view->registerJs(<<<JS
90
        // Checkbox
91
        var checkboxes = $('table input[type="checkbox"]');
92
        var bulkcontainer = $('.box-bulk-actions fieldset');
93
        checkboxes.on('ifChecked ifUnchecked', function(event) {
94
            if (event.type == 'ifChecked' && $('input.icheck').filter(':checked').length > 0) {
95
                bulkcontainer.prop('disabled', false);
96
            } else if ($('input.icheck').filter(':checked').length == 0) {
97
                bulkcontainer.prop('disabled', true);
98
            }
99
        });
100
        // On/Off Actions TODO: reduce scope
101
        $(document).on('click', '.box-bulk-actions a', function (event) {
102
            var link = $(this);
103
            var action = link.data('action');
104
            var form = $($searchFormId);
105
            if (action) {
106
                form.attr({'action': action, method: 'POST'}).submit();
107
            }
108
        });
109
JS
110
);
111
    }
112
113
    /**
114
     * Begins output buffer capture to save data in [[contents]] with the $name key.
115
     * Must not be called nested. See [[endContent]] for capture terminating.
116
     * @param string $name
117
     */
118
    public function beginContent($name)
119
    {
120
        if ($this->_current) {
121
            throw new InvalidParamException('Output buffer capture is already running for ' . $this->_current);
122
        }
123
        $this->_current = $name;
124
        ob_start();
125
        ob_implicit_flush(false);
126
    }
127
128
    /**
129
     * Terminates output buffer capture started by [[beginContent()]].
130
     * @see beginContent
131
     */
132
    public function endContent()
133
    {
134
        if (!$this->_current) {
135
            throw new InvalidParamException('Outout buffer capture is not running. Call beginContent() first');
136
        }
137
        $this->contents[$this->_current] = ob_get_contents();
138
        ob_end_clean();
139
        $this->_current = null;
140
    }
141
142
    /**
143
     * Returns content saved in [[content]] by $name.
144
     * @param string $name
145
     * @return string
146
     */
147
    public function renderContent($name)
148
    {
149
        return $this->contents[$name];
150
    }
151
152
    public function run()
153
    {
154
        return $this->render($this->getLayout());
155
    }
156
157
    public function detectLayout()
158
    {
159
        $os = Yii::$app->get('orientationStorage');
160
        $n = $os->get(Yii::$app->controller->getRoute());
161
        return $n;
162
    }
163
164
    public function setSearchFormData($data = [])
165
    {
166
        $this->searchFormData = $data;
167
    }
168
169
    public function setSearchFormOptions($options = [])
170
    {
171
        $this->searchFormOptions = $options;
172
    }
173
174
    public function renderSearchForm($advancedSearchOptions = [])
175
    {
176
        $advancedSearchOptions = array_merge($advancedSearchOptions, $this->searchFormOptions);
177
        ob_start();
178
        ob_implicit_flush(false);
179
        try {
180
            $search = $this->beginSearchForm($advancedSearchOptions);
181
            foreach (['per_page', 'representation'] as $key) {
182
                echo Html::hiddenInput($key, Yii::$app->request->get($key));
183
            }
184
            echo Yii::$app->view->render($this->searchView, array_merge(compact('search'), $this->searchFormData), $this->originalContext);
185
            $search->end();
186
        } catch (\Exception $e) {
187
            ob_end_clean();
188
            throw $e;
189
        }
190
191
        return ob_get_clean();
192
    }
193
194
    public function beginSearchForm($options = [])
195
    {
196
        return AdvancedSearch::begin(array_merge(['model' => $this->model], $options));
197
    }
198
199
    public function renderSearchButton()
200
    {
201
        return AdvancedSearch::renderButton() . "\n";
202
    }
203
204
    public function renderLayoutSwitcher()
205
    {
206
        return IndexLayoutSwitcher::widget();
207
    }
208
209 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...
210
    {
211
        return ButtonDropdown::widget([
212
            'label' => Yii::t('hipanel', 'Per page') . ': ' . (Yii::$app->request->get('per_page') ?: 25),
213
            'options' => ['class' => 'btn-default btn-sm'],
214
            'dropdown' => [
215
                'items' => [
216
                    ['label' => '25',  'url' => Url::current(['per_page' => null])],
217
                    ['label' => '50',  'url' => Url::current(['per_page' => 50])],
218
                    ['label' => '100', 'url' => Url::current(['per_page' => 100])],
219
                    ['label' => '200', 'url' => Url::current(['per_page' => 200])],
220
                    ['label' => '500', 'url' => Url::current(['per_page' => 500])],
221
                ],
222
            ],
223
        ]);
224
    }
225
226
    /**
227
     * Renders button to choose representation.
228
     * Returns empty string when nothing to choose (less then 2 representations available).
229
     * @param array $grid class
230
     * @param mixed $current selected representation
231
     * @return string rendered HTML
232
     */
233
    public static function renderRepresentations($grid, $current)
234
    {
235
        $representations = $grid::getRepresentations();
236
        if (count($representations)<2) {
237
            return '';
238
        }
239
        if (!isset($representations[$current])) {
240
            $current = key($representations);
241
        }
242
        $items = [];
243
        foreach ($representations as $key => $data) {
244
            $items[] = [
245
                'label' => $data['label'],
246
                'url'   => Url::current(['representation' => $key]),
247
            ];
248
        }
249
250
        return ButtonDropdown::widget([
251
            'label' => Yii::t('synt', 'View') . ': ' . $representations[$current]['label'],
252
            'options' => ['class' => 'btn-default btn-sm'],
253
            'dropdown' => [
254
                'items' => $items,
255
            ],
256
        ]);
257
    }
258
259 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...
260
    {
261
        return LinkSorter::widget(array_merge([
262
            'show'  => true,
263
            'sort'  => $this->dataProvider->getSort(),
264
            'buttonClass' => 'btn btn-default dropdown-toggle btn-sm',
265
        ], $options));
266
    }
267
268
    public function getViewPath()
269
    {
270
        return parent::getViewPath() . DIRECTORY_SEPARATOR . (new \ReflectionClass($this))->getShortName();
271
    }
272
273
    public function getBulkFormId()
274
    {
275
        return 'bulk-' . Inflector::camel2id($this->model->formName());
276
    }
277
278
    public function beginBulkForm($action = '')
279
    {
280
        echo Html::beginForm($action, 'POST', ['id' => $this->getBulkFormId()]);
281
    }
282
283
    public function endBulkForm()
284
    {
285
        echo Html::endForm();
286
    }
287
288 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...
289
    {
290
        return Html::submitButton($text, [
291
            'class'         => "btn btn-$color btn-sm",
292
            'form'          => $this->getBulkFormId(),
293
            'formmethod'    => 'POST',
294
            'formaction'    => $action,
295
        ]);
296
    }
297
298
    /**
299
     * @return string
300
     */
301
    public function getLayout()
302
    {
303
        if ($this->_layout === null) {
304
            $this->_layout = $this->detectLayout();
305
        }
306
        return $this->_layout;
307
    }
308
309
    /**
310
     * @param string $layout
311
     */
312
    public function setLayout($layout)
313
    {
314
        $this->_layout = $layout;
315
    }
316
}
317