Test Setup Failed
Push — master ( d219f7...aa460f )
by eXeCUT
13:22
created

DynaGrid   B

Complexity

Total Complexity 39

Size/Duplication

Total Lines 325
Duplicated Lines 10.46 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 39
c 3
b 0
f 1
lcom 2
cbo 3
dl 34
loc 325
rs 8.2857

14 Methods

Rating   Name   Duplication   Size   Complexity  
B renderMassEditButton() 0 30 2
B renderVisibleButtons() 0 34 5
B getDefaultWidgetOptions() 0 24 1
A getWidgetOptions() 0 11 2
A getDynaGridId() 0 10 2
A getGridId() 0 3 1
B renderAlertBlock() 34 34 5
B getToolbarConfig() 0 24 3
A lcfirst() 0 6 1
A getUniqueId() 0 7 2
C getUrlAttributes() 0 43 11
A renderAddButton() 0 14 2
A getUpdateUrlParams() 0 6 1
A getAddUrlParams() 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
 * User: execut
4
 * Date: 21.07.16
5
 * Time: 13:32
6
 */
7
8
namespace execut\actions\action\adapter\viewRenderer;
9
10
11
use yii\db\ActiveRecord;
12
use yii\helpers\ArrayHelper;
13
use yii\helpers\Html;
14
use kartik\export\ExportMenu;
15
use yii\bootstrap\Alert;
16
use yii\data\BaseDataProvider;
17
use yii\helpers\Url;
18
use yii\web\JsExpression;
19
20
class DynaGrid extends Widget
21
{
22
    public $title = null;
23
    public $modelClass = null;
24
    /**
25
     * @var BaseDataProvider
26
     */
27
    public $dataProvider = null;
28
29
    /**
30
     * @var ActiveRecord
31
     */
32
    public $filter = null;
33
    public $uniqueId = null;
34
    public $urlAttributes = null;
35
    public $isAllowedAdding = true;
36
    public $isAllowedMassEdit = false;
37
    public $refreshAttributes = [];
38
    public $handleButtons = [];
39
    public $isRenderFlashes = true;
40
    public $urlAttributesExcluded = [];
41
    public $defaultHandleButtons = [
42
        'visible' => [
43
            'icon' => 'eye-open',
44
            'label' => 'Mark visible',
45
            'confirmMessage' => 'You sure want mark # records as visible?',
46
            'enable' => false,
47
        ],
48
        'unvisible' => [
49
            'icon' => 'eye-close',
50
            'label' => 'Mark unvisible',
51
            'confirmMessage' => 'You sure want mark # records as unvisible?',
52
            'enable' => false,
53
        ],
54
        'delete' => [
55
            'icon' => 'trash',
56
            'label' => 'Delete',
57
            'button' => 'danger',
58
            'confirmMessage' => 'You sure want delete # records?',
59
            'enable' => false,
60
        ],
61
    ];
62
    public function getDefaultWidgetOptions()
63
    {
64
        return [
65
            'class' => \execut\actions\widgets\DynaGrid::class,
66
            'filter' => $this->filter,
67
            'dataProvider' => $this->dataProvider,
68
            'gridOptions' => [
69
                'updateUrl' => $this->getUpdateUrlParams(),
70
                'addButtonUrl' => $this->getAddUrlParams(),
71
                'layout' => '{alertBlock}<div class="dyna-grid-footer">{summary}{pager}<div class="dyna-grid-toolbar">{toolbar}</div></div>{items}',
72
                'toolbar' => $this->getToolbarConfig(),
73
//                'panel' => [
0 ignored issues
show
Unused Code Comprehensibility introduced by
48% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
74
//                    'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-cog"></i> ' . \yii::t('execut.actions', 'List') . ' ' . $this->lcfirst($this->title) . '</h3>',
75
//                    'before' => $alertBlock,
76
//                ],
77
                'options' => [
78
                    'id' => $this->getGridId(),
79
                ],
80
            ],
81
            'options' => [
82
                'id' => $this->getDynaGridId(),
83
            ],
84
        ];
85
    }
86
87
    public function getWidgetOptions()
88
    {
89
        $options = parent::getWidgetOptions();
90
        if (!empty($options['gridOptions']['layout'])) {
91
            $options['gridOptions']['layout'] = strtr($options['gridOptions']['layout'], [
92
                '{alertBlock}' => $this->renderAlertBlock(),
93
            ]);
94
        }
95
96
        return $options;
97
    }
98
99
    protected function getDynaGridId() {
100
        $m = $this->modelClass;
101
        $tableName = str_replace('\\', '_', $m) . '1';
102
        $userId = '';
103
        if (\yii::$app->user) {
104
            $userId .= \yii::$app->user->id;
105
        }
106
107
        return 'dynagrid-' . $tableName . '-' . $userId;
108
    }
109
110
    protected function getGridId() {
111
        return 'grid-' . $this->getDynaGridId();
112
    }
113
114 View Code Duplication
    protected function renderAlertBlock()
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...
115
    {
116
        if (!$this->isRenderFlashes) {
117
            return '';
118
        }
119
120
        $session = \Yii::$app->session;
121
        $flashes = $session->getAllFlashes();
122
        $alertContainerOptions = [
123
            'style' => 'max-width:400px'
124
        ];
125
        if (count($flashes) === 0) {
126
            Html::addCssStyle($alertContainerOptions, 'display:none;');
127
        }
128
        $out = Html::beginTag('div', $alertContainerOptions);
129
        foreach ($flashes as $type => $message) {
130
            if (is_array($message)) {
131
                $message = implode('<br>', $message);
132
            }
133
134
            $alertWidgetOptions = [];
135
            $alertWidgetOptions['body'] = $message;
136
            $alertWidgetOptions['options'] = [
137
                'class' => ['alert', 'alert-success'],
138
                'style' => 'padding-left:10px;padding-right:10px;'
139
            ];
140
            $out .= "\n" . Alert::widget($alertWidgetOptions);
141
            $session->removeFlash($type);
142
        }
143
144
        $out .= "\n</div>";
145
146
        return $out;
147
    }
148
149
    /**
150
     * @param $refreshUrlParams
151
     * @return array
152
     */
153
    public function getToolbarConfig(): array
154
    {
155
        $refreshUrlParams = [
156
            $this->adapter->uniqueId,
157
        ];
158
159
        foreach ($this->refreshAttributes as $key) {
160
            if (!empty($this->adapter->actionParams->get[$key])) {
161
                $refreshUrlParams[$key] = $this->adapter->actionParams->get[$key];
162
            }
163
        }
164
165
        return [
166
            'massEdit' => ['content' => $this->renderMassEditButton()],
167
            'massVisible' => ['content' => $this->renderVisibleButtons()],
168
            'add' => ['content' => $this->renderAddButton()],
169
            'refresh' => [
170
                'content' => Html::a('<i class="glyphicon glyphicon-repeat"></i>', $refreshUrlParams, ['data-pjax' => 0, 'class' => 'btn btn-default', 'title' => 'Reset Grid']),
171
            ],
172
            'dynaParams' => ['content' => '{dynagridFilter}{dynagridSort}{dynagrid}'],
173
            'toggleData' => '{toggleData}',
174
            'export' => '{export}',
175
        ];
176
    }
177
178
    protected function lcfirst($string, $encoding = "UTF-8")
179
    {
180
        $first = mb_convert_case(mb_substr($string, 0, 1, $encoding), MB_CASE_LOWER, $encoding);
181
182
        return $first . mb_substr($string, 1, null, $encoding);
183
    }
184
185
    public function getUniqueId() {
186
        if ($this->uniqueId) {
187
            return $this->uniqueId;
188
        } else {
189
            return $this->adapter->actionParams->getUniqueId(['module', 'controller']);
190
        }
191
    }
192
193
    protected function getUrlAttributes() {
194
195
        if ($this->urlAttributes === null) {
196
            $filterAttributes = $this->filter->attributes;
197
            foreach ($this->filter->getRelatedRecords() as $relation => $records) {
198
                if (empty($records)) {
199
                    continue;
200
                }
201
202
                if (!is_array($records)) {
203
                    $filterAttributes[$relation] = $records;
204
                    continue;
205
                }
206
207
                $relationAttributes = [];
208
                foreach ($records as $key => $record) {
209
                    $recordAttributes = array_filter($record->attributes);
210
                    if (!empty($recordAttributes)) {
211
                        $relationAttributes[$key] = $recordAttributes;
212
                    }
213
                }
214
215
                if (!empty($relationAttributes)) {
216
                    $filterAttributes[$relation] = $relationAttributes;
217
                }
218
            }
219
220
            $formName = $this->filter->formName();
221
            $result = [$formName => []];
222
            foreach ($filterAttributes as $attribute => $value) {
223
                if (in_array($attribute, $this->urlAttributesExcluded)) {
224
                    continue;
225
                }
226
                if (!empty($value)) {
227
                    $result[$formName][$attribute] = $value;
228
                }
229
            }
230
231
            return $result;
232
        }
233
234
        return $this->urlAttributes;
235
    }
236
237
    /**
238
     * @return string
239
     */
240
    protected function renderAddButton()
241
    {
242
        if ($this->isAllowedAdding) {
243
            $lcfirstTitle = $this->title;
244
//            var_dump($lcfirstTitle);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
245
//            exit;
246
            return Html::a(\yii::t('execut.actions', 'Add') . ' ' . $lcfirstTitle, Url::to($this->getUpdateUrlParams()), [
247
                    'type' => 'button',
248
                    'data-pjax' => 0,
249
                    'title' => \yii::t('execut.actions', 'Add') . ' ' . $lcfirstTitle,
250
                    'class' => 'btn btn-success'
251
                ]) . ' ';
252
        }
253
    }
254
255
    /**
256
     * @return string
257
     */
258
    protected function renderMassEditButton()
259
    {
260
        if ($this->isAllowedMassEdit) {
261
            $lcfirstTitle = $this->title;
0 ignored issues
show
Unused Code introduced by
$lcfirstTitle is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
262
263
            return \mickgeek\actionbar\Widget::widget([
264
                'renderContainer' => false,
265
                'grid' => $this->getGridId(),
266
                'templates' => [
267
                    '{bulk-actions}' => [
268
//                        'class' => 'col-xs-4'
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
269
                    ],
270
//                    '{create}' => ['class' => 'col-xs-8 text-right'],
0 ignored issues
show
Unused Code Comprehensibility introduced by
62% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
271
                ],
272
                'bulkActionsItems' => [
273
                    'General' => ['mass-update' => 'Mass edit',],
274
                ],
275
                'bulkActionsOptions' => [
276
                    'options' => [
277
                        'mass-update' => [
278
                            'url' => Url::toRoute(['mass-update']),
279
                            'method' => 'get',
280
                            'name' => 'id',
281
                        ],
282
                    ],
283
                    'class' => 'form-control',
284
                ],
285
            ]);
286
        }
287
    }
288
289
    /**
290
     * @return string
291
     */
292
    protected function renderVisibleButtons(): string
293
    {
294
        $buttons = '';
295
        $handleButtons = ArrayHelper::merge($this->defaultHandleButtons, $this->handleButtons);
296
        foreach ($handleButtons as $handle => $buttonOptions) {
297
            if (isset($buttonOptions['enable']) && $buttonOptions['enable'] === false) {
298
                continue;
299
            }
300
301
            $urlParams = \yii::$app->request->getQueryParams();
302
            $urlParams[0] = '';
303
            $urlParams['handle'] = $handle;
304
            $buttonClass = 'default';
305
            if (!empty($buttonOptions['button'])) {
306
                $buttonClass = $buttonOptions['button'];
307
            }
308
309
            $icon = $buttonOptions['icon'];
310
            $confirmMessage = strtr($buttonOptions['confirmMessage'], ['#' => (string) $this->dataProvider->getTotalCount()]);
311
            $buttons .= Html::a('<i class="glyphicon glyphicon-' . $icon . '"></i>', Url::to($urlParams), [
312
                'type' => 'button',
313
                'onclick' => new JsExpression(<<<JS
314
return confirm('$confirmMessage');
315
JS
316
),
317
                'data-pjax' => 0,
318
                'title' => $buttonOptions['label'],
319
                'class' => 'btn btn-' . $buttonClass
320
            ]);
321
322
        }
323
324
        return $buttons;
325
    }
326
327
    /**
328
     * @return array
329
     */
330
    protected function getUpdateUrlParams(): array
331
    {
332
        return [
333
            '/' . trim($this->getUniqueId(), '/') . '/update',
334
        ];
335
    }
336
337
    /**
338
     * @return array
339
     */
340
    protected function getAddUrlParams(): array
341
    {
342
        return array_merge($this->getUpdateUrlParams(), $this->getUrlAttributes());
343
    }
344
}