Test Setup Failed
Push — master ( ecc121...dee8f4 )
by eXeCUT
12:00
created

DynaGrid::getWidgetOptions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 11
rs 9.4285
cc 2
eloc 6
nc 2
nop 0
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
        $columns = $this->filter->getGridColumns();
65
//        $flash = '<aasd';
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
66
        $fullExportMenu = ExportMenu::widget([
67
            'dataProvider' => $this->dataProvider,
68
//            'dataProvider' => $dataProvider,
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
69
            'columns' => $columns,
70
            'target' => ExportMenu::TARGET_BLANK,
71
            'batchSize' => 1000,
72
            'fontAwesome' => true,
73
            'asDropdown' => false, // this is important for this case so we just need to get a HTML list
74
            'dropdownOptions' => [
75
                'label' => '<i class="glyphicon glyphicon-export"></i> Full'
76
            ],
77
        ]);
78
79
        return [
80
            'class' => \execut\actions\widgets\DynaGrid::class,
81
            'storage' => \kartik\dynagrid\DynaGrid::TYPE_DB,
82
//            'pageSize' => 100000,
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% 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...
83
            'gridOptions' => [
84
                'responsive' => false,
85
                'responsiveWrap' => false,
86
                'rowOptions' => function ($row) {
87
                    if (method_exists($row, 'getRowOptions')) {
88
                        return $row->getRowOptions();
89
                    }
90
                },
91
                'panel' => false,
92
                'layout' => '{alertBlock}<div class="dyna-grid-footer">{summary}{pager}<div class="dyna-grid-toolbar">{toolbar}</div></div>{items}',
93
//                'floatHeader' => true,
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...
94
//                'floatHeaderOptions' => [
95
//                    'top' => 0,
96
//                    'zIndex' => 10000,
97
//                ],
98
                'export' => [
99
                    'fontAwesome' => true,
100
                    'itemsAfter'=> [
101
                        '<li role="presentation" class="divider"></li>',
102
                        '<li class="dropdown-header">Export All Data</li>',
103
                        $fullExportMenu
104
                    ]
105
                ],
106
                'toggleDataOptions' => [
107
                    'maxCount' => 100000,
108
//                    'all' => [
0 ignored issues
show
Unused Code Comprehensibility introduced by
49% 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...
109
//                       'icon' => 'resize-full',
110
//                       'label' => 'All',
111
//                       'class' => 'btn btn-default',
112
//                       'title' => 'Show all data'
113
//                    ],
114
                ],
115
                'filterModel' => $this->filter,
116
                'toolbar' => $this->getToolbarConfig(),
117
//                '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...
118
//                    'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-cog"></i> ' . \yii::t('execut.actions', 'List') . ' ' . $this->lcfirst($this->title) . '</h3>',
119
//                    'before' => $alertBlock,
120
//                ],
121
                'dataProvider' => $this->dataProvider,
122
                'options' => [
123
                    'id' => $this->getGridId(),
124
                ],
125
            ],
126
            'options' => [
127
                'id' => $this->getDynaGridId(),
128
            ],
129
            'columns' => $columns,
130
        ];
131
    }
132
133
    public function getWidgetOptions()
134
    {
135
        $options = parent::getWidgetOptions();
136
        if (!empty($options['gridOptions']['layout'])) {
137
            $options['gridOptions']['layout'] = strtr($options['gridOptions']['layout'], [
138
                '{alertBlock}' => $this->renderAlertBlock(),
139
            ]);
140
        }
141
142
        return $options;
143
    }
144
145
    protected function getDynaGridId() {
146
        $m = $this->modelClass;
147
        $tableName = str_replace('\\', '_', $m) . '1';
148
        $userId = '';
149
        if (\yii::$app->user) {
150
            $userId .= \yii::$app->user->id;
151
        }
152
153
        return 'dynagrid-' . $tableName . '-' . $userId;
154
    }
155
156
    protected function getGridId() {
157
        return 'grid-' . $this->getDynaGridId();
158
    }
159
160 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...
161
    {
162
        if (!$this->isRenderFlashes) {
163
            return '';
164
        }
165
166
        $session = \Yii::$app->session;
167
        $flashes = $session->getAllFlashes();
168
        $alertContainerOptions = [
169
            'style' => 'max-width:400px'
170
        ];
171
        if (count($flashes) === 0) {
172
            Html::addCssStyle($alertContainerOptions, 'display:none;');
173
        }
174
        $out = Html::beginTag('div', $alertContainerOptions);
175
        foreach ($flashes as $type => $message) {
176
            if (is_array($message)) {
177
                $message = implode('<br>', $message);
178
            }
179
180
            $alertWidgetOptions = [];
181
            $alertWidgetOptions['body'] = $message;
182
            $alertWidgetOptions['options'] = [
183
                'class' => ['alert', 'alert-success'],
184
                'style' => 'padding-left:10px;padding-right:10px;'
185
            ];
186
            $out .= "\n" . Alert::widget($alertWidgetOptions);
187
            $session->removeFlash($type);
188
        }
189
190
        $out .= "\n</div>";
191
192
        return $out;
193
    }
194
195
    /**
196
     * @param $refreshUrlParams
197
     * @return array
198
     */
199
    public function getToolbarConfig(): array
200
    {
201
        $refreshUrlParams = [
202
            $this->adapter->uniqueId,
203
        ];
204
205
        foreach ($this->refreshAttributes as $key) {
206
            if (!empty($this->adapter->actionParams->get[$key])) {
207
                $refreshUrlParams[$key] = $this->adapter->actionParams->get[$key];
208
            }
209
        }
210
211
        return [
212
            'massEdit' => ['content' => $this->renderMassEditButton()],
213
            'massVisible' => ['content' => $this->renderVisibleButtons()],
214
            'add' => ['content' => $this->renderAddButton()],
215
            'refresh' => [
216
                'content' => Html::a('<i class="glyphicon glyphicon-repeat"></i>', $refreshUrlParams, ['data-pjax' => 0, 'class' => 'btn btn-default', 'title' => 'Reset Grid']),
217
            ],
218
            'dynaParams' => ['content' => '{dynagridFilter}{dynagridSort}{dynagrid}'],
219
            'toggleData' => '{toggleData}',
220
            'export' => '{export}',
221
        ];
222
    }
223
224
    protected function lcfirst($string, $encoding = "UTF-8")
225
    {
226
        $first = mb_convert_case(mb_substr($string, 0, 1, $encoding), MB_CASE_LOWER, $encoding);
227
228
        return $first . mb_substr($string, 1, null, $encoding);
229
    }
230
231
    public function getUniqueId() {
232
        if ($this->uniqueId) {
233
            return $this->uniqueId;
234
        } else {
235
            return $this->adapter->actionParams->getUniqueId(['module', 'controller']);
236
        }
237
    }
238
239
    protected function getUrlAttributes() {
240
241
        if ($this->urlAttributes === null) {
242
            $filterAttributes = $this->filter->attributes;
243
            foreach ($this->filter->getRelatedRecords() as $relation => $records) {
244
                if (empty($records)) {
245
                    continue;
246
                }
247
248
                if (!is_array($records)) {
249
                    $filterAttributes[$relation] = $records;
250
                    continue;
251
                }
252
253
                $relationAttributes = [];
254
                foreach ($records as $key => $record) {
255
                    $recordAttributes = array_filter($record->attributes);
256
                    if (!empty($recordAttributes)) {
257
                        $relationAttributes[$key] = $recordAttributes;
258
                    }
259
                }
260
261
                if (!empty($relationAttributes)) {
262
                    $filterAttributes[$relation] = $relationAttributes;
263
                }
264
            }
265
266
            $formName = $this->filter->formName();
267
            $result = [$formName => []];
268
            foreach ($filterAttributes as $attribute => $value) {
269
                if (in_array($attribute, $this->urlAttributesExcluded)) {
270
                    continue;
271
                }
272
                if (!empty($value)) {
273
                    $result[$formName][$attribute] = $value;
274
                }
275
            }
276
277
            return $result;
278
        }
279
280
        return $this->urlAttributes;
281
    }
282
283
    /**
284
     * @return string
285
     */
286
    protected function renderAddButton()
287
    {
288
        if ($this->isAllowedAdding) {
289
            $lcfirstTitle = $this->title;
290
//            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...
291
//            exit;
292
            return Html::a(\yii::t('execut.actions', 'Add') . ' ' . $lcfirstTitle, Url::to(array_merge([
293
                    '/' . $this->getUniqueId() . '/update',
294
                ], $this->getUrlAttributes())), [
295
                    'type' => 'button',
296
                    'data-pjax' => 0,
297
                    'title' => \yii::t('execut.actions', 'Add') . ' ' . $lcfirstTitle,
298
                    'class' => 'btn btn-success'
299
                ]) . ' ';
300
        }
301
    }
302
303
    /**
304
     * @return string
305
     */
306
    protected function renderMassEditButton()
307
    {
308
        if ($this->isAllowedMassEdit) {
309
            $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...
310
311
            return \mickgeek\actionbar\Widget::widget([
312
                'renderContainer' => false,
313
                'grid' => $this->getGridId(),
314
                'templates' => [
315
                    '{bulk-actions}' => [
316
//                        '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...
317
                    ],
318
//                    '{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...
319
                ],
320
                'bulkActionsItems' => [
321
                    'General' => ['mass-update' => 'Mass edit',],
322
                ],
323
                'bulkActionsOptions' => [
324
                    'options' => [
325
                        'mass-update' => [
326
                            'url' => Url::toRoute(['mass-update']),
327
                            'method' => 'get',
328
                            'name' => 'id',
329
                        ],
330
                    ],
331
                    'class' => 'form-control',
332
                ],
333
            ]);
334
        }
335
    }
336
337
    /**
338
     * @return string
339
     */
340
    protected function renderVisibleButtons(): string
341
    {
342
        $buttons = '';
343
        $handleButtons = ArrayHelper::merge($this->defaultHandleButtons, $this->handleButtons);
344
        foreach ($handleButtons as $handle => $buttonOptions) {
345
            if (isset($buttonOptions['enable']) && $buttonOptions['enable'] === false) {
346
                continue;
347
            }
348
349
            $urlParams = \yii::$app->request->getQueryParams();
350
            $urlParams[0] = '';
351
            $urlParams['handle'] = $handle;
352
            $buttonClass = 'default';
353
            if (!empty($buttonOptions['button'])) {
354
                $buttonClass = $buttonOptions['button'];
355
            }
356
357
            $icon = $buttonOptions['icon'];
358
            $confirmMessage = strtr($buttonOptions['confirmMessage'], ['#' => (string) $this->dataProvider->getTotalCount()]);
359
            $buttons .= Html::a('<i class="glyphicon glyphicon-' . $icon . '"></i>', Url::to($urlParams), [
360
                'type' => 'button',
361
                'onclick' => new JsExpression(<<<JS
362
return confirm('$confirmMessage');
363
JS
364
),
365
                'data-pjax' => 0,
366
                'title' => $buttonOptions['label'],
367
                'class' => 'btn btn-' . $buttonClass
368
            ]);
369
370
        }
371
372
        return $buttons;
373
    }
374
}