GridView   F
last analyzed

Complexity

Total Complexity 64

Size/Duplication

Total Lines 546
Duplicated Lines 0 %

Test Coverage

Coverage 79.61%

Importance

Changes 0
Metric Value
eloc 168
dl 0
loc 546
ccs 121
cts 152
cp 0.7961
rs 3.28
c 0
b 0
f 0
wmc 64

16 Methods

Rating   Name   Duplication   Size   Complexity  
A renderErrors() 0 7 3
A renderTableFooter() 0 13 3
A createDataColumn() 0 12 5
A renderFilters() 0 13 3
B guessColumns() 0 8 7
A renderTableRow() 0 15 4
A run() 0 8 1
A init() 0 16 5
A renderTableHeader() 0 15 4
A renderColumnGroup() 0 15 4
A renderCaption() 0 7 2
B renderTableBody() 0 31 8
A getClientOptions() 0 12 3
A renderSection() 0 7 2
A initColumns() 0 19 6
A renderItems() 0 28 4

How to fix   Complexity   

Complex Class

Complex classes like GridView often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use GridView, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\grid;
10
11
use Closure;
12
use Yii;
13
use yii\base\InvalidConfigException;
14
use yii\base\Model;
15
use yii\helpers\Html;
16
use yii\helpers\Json;
17
use yii\helpers\Url;
18
use yii\i18n\Formatter;
19
use yii\widgets\BaseListView;
20
21
/**
22
 * The GridView widget is used to display data in a grid.
23
 *
24
 * It provides features like [[sorter|sorting]], [[pager|paging]] and also [[filterModel|filtering]] the data.
25
 *
26
 * A basic usage looks like the following:
27
 *
28
 * ```php
29
 * <?= GridView::widget([
30
 *     'dataProvider' => $dataProvider,
31
 *     'columns' => [
32
 *         'id',
33
 *         'name',
34
 *         'created_at:datetime',
35
 *         // ...
36
 *     ],
37
 * ]) ?>
38
 * ```
39
 *
40
 * The columns of the grid table are configured in terms of [[Column]] classes,
41
 * which are configured via [[columns]].
42
 *
43
 * The look and feel of a grid view can be customized using the large amount of properties.
44
 *
45
 * For more details and usage information on GridView, see the [guide article on data widgets](guide:output-data-widgets).
46
 *
47
 * @author Qiang Xue <[email protected]>
48
 * @since 2.0
49
 */
50
class GridView extends BaseListView
51
{
52
    const FILTER_POS_HEADER = 'header';
53
    const FILTER_POS_FOOTER = 'footer';
54
    const FILTER_POS_BODY = 'body';
55
56
    /**
57
     * @var string the default data column class if the class name is not explicitly specified when configuring a data column.
58
     * Defaults to 'yii\grid\DataColumn'.
59
     */
60
    public $dataColumnClass;
61
    /**
62
     * @var string the caption of the grid table
63
     * @see captionOptions
64
     */
65
    public $caption;
66
    /**
67
     * @var array the HTML attributes for the caption element.
68
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
69
     * @see caption
70
     */
71
    public $captionOptions = [];
72
    /**
73
     * @var array the HTML attributes for the grid table element.
74
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
75
     */
76
    public $tableOptions = ['class' => 'table table-striped table-bordered'];
77
    /**
78
     * @var array the HTML attributes for the container tag of the grid view.
79
     * The "tag" element specifies the tag name of the container element and defaults to "div".
80
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
81
     */
82
    public $options = ['class' => 'grid-view'];
83
    /**
84
     * @var array the HTML attributes for the table header row.
85
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
86
     */
87
    public $headerRowOptions = [];
88
    /**
89
     * @var array the HTML attributes for the table footer row.
90
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
91
     */
92
    public $footerRowOptions = [];
93
    /**
94
     * @var array|Closure the HTML attributes for the table body rows. This can be either an array
95
     * specifying the common HTML attributes for all body rows, or an anonymous function that
96
     * returns an array of the HTML attributes. The anonymous function will be called once for every
97
     * data model returned by [[dataProvider]]. It should have the following signature:
98
     *
99
     * ```php
100
     * function ($model, $key, $index, $grid)
101
     * ```
102
     *
103
     * - `$model`: the current data model being rendered
104
     * - `$key`: the key value associated with the current data model
105
     * - `$index`: the zero-based index of the data model in the model array returned by [[dataProvider]]
106
     * - `$grid`: the GridView object
107
     *
108
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
109
     */
110
    public $rowOptions = [];
111
    /**
112
     * @var Closure an anonymous function that is called once BEFORE rendering each data model.
113
     * It should have the similar signature as [[rowOptions]]. The return result of the function
114
     * will be rendered directly.
115
     */
116
    public $beforeRow;
117
    /**
118
     * @var Closure an anonymous function that is called once AFTER rendering each data model.
119
     * It should have the similar signature as [[rowOptions]]. The return result of the function
120
     * will be rendered directly.
121
     */
122
    public $afterRow;
123
    /**
124
     * @var bool whether to show the header section of the grid table.
125
     */
126
    public $showHeader = true;
127
    /**
128
     * @var bool whether to show the footer section of the grid table.
129
     */
130
    public $showFooter = false;
131
    /**
132
     * @var bool whether to place footer after body in DOM if $showFooter is true
133
     * @since 2.0.14
134
     */
135
    public $placeFooterAfterBody = false;
136
    /**
137
     * @var bool whether to show the grid view if [[dataProvider]] returns no data.
138
     */
139
    public $showOnEmpty = true;
140
    /**
141
     * @var array|Formatter|null the formatter used to format model attribute values into displayable texts.
142
     * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
143
     * instance. If this property is not set, the "formatter" application component will be used.
144
     */
145
    public $formatter;
146
    /**
147
     * @var array grid column configuration. Each array element represents the configuration
148
     * for one particular grid column. For example,
149
     *
150
     * ```php
151
     * [
152
     *     ['class' => SerialColumn::class],
153
     *     [
154
     *         'class' => DataColumn::class, // this line is optional
155
     *         'attribute' => 'name',
156
     *         'format' => 'text',
157
     *         'label' => 'Name',
158
     *     ],
159
     *     ['class' => CheckboxColumn::class],
160
     * ]
161
     * ```
162
     *
163
     * If a column is of class [[DataColumn]], the "class" element can be omitted.
164
     *
165
     * As a shortcut format, a string may be used to specify the configuration of a data column
166
     * which only contains [[DataColumn::attribute|attribute]], [[DataColumn::format|format]],
167
     * and/or [[DataColumn::label|label]] options: `"attribute:format:label"`.
168
     * For example, the above "name" column can also be specified as: `"name:text:Name"`.
169
     * Both "format" and "label" are optional. They will take default values if absent.
170
     *
171
     * Using the shortcut format the configuration for columns in simple cases would look like this:
172
     *
173
     * ```php
174
     * [
175
     *     'id',
176
     *     'amount:currency:Total Amount',
177
     *     'created_at:datetime',
178
     * ]
179
     * ```
180
     *
181
     * When using a [[dataProvider]] with active records, you can also display values from related records,
182
     * e.g. the `name` attribute of the `author` relation:
183
     *
184
     * ```php
185
     * // shortcut syntax
186
     * 'author.name',
187
     * // full syntax
188
     * [
189
     *     'attribute' => 'author.name',
190
     *     // ...
191
     * ]
192
     * ```
193
     */
194
    public $columns = [];
195
    /**
196
     * @var string the HTML display when the content of a cell is empty.
197
     * This property is used to render cells that have no defined content,
198
     * e.g. empty footer or filter cells.
199
     *
200
     * Note that this is not used by the [[DataColumn]] if a data item is `null`. In that case
201
     * the [[\yii\i18n\Formatter::nullDisplay|nullDisplay]] property of the [[formatter]] will
202
     * be used to indicate an empty data value.
203
     */
204
    public $emptyCell = '&nbsp;';
205
    /**
206
     * @var \yii\base\Model|null the model that keeps the user-entered filter data. When this property is set,
207
     * the grid view will enable column-based filtering. Each data column by default will display a text field
208
     * at the top that users can fill in to filter the data.
209
     *
210
     * Note that in order to show an input field for filtering, a column must have its [[DataColumn::attribute]]
211
     * property set and the attribute should be active in the current scenario of $filterModel or have
212
     * [[DataColumn::filter]] set as the HTML code for the input field.
213
     *
214
     * When this property is not set (null) the filtering feature is disabled.
215
     */
216
    public $filterModel;
217
    /**
218
     * @var string|array|null the URL for returning the filtering result. [[Url::to()]] will be called to
219
     * normalize the URL. If not set, the current controller action will be used.
220
     * When the user makes change to any filter input, the current filtering inputs will be appended
221
     * as GET parameters to this URL.
222
     */
223
    public $filterUrl;
224
    /**
225
     * @var string additional jQuery selector for selecting filter input fields
226
     */
227
    public $filterSelector;
228
    /**
229
     * @var string whether the filters should be displayed in the grid view. Valid values include:
230
     *
231
     * - [[FILTER_POS_HEADER]]: the filters will be displayed on top of each column's header cell.
232
     * - [[FILTER_POS_BODY]]: the filters will be displayed right below each column's header cell.
233
     * - [[FILTER_POS_FOOTER]]: the filters will be displayed below each column's footer cell.
234
     */
235
    public $filterPosition = self::FILTER_POS_BODY;
236
    /**
237
     * @var array the HTML attributes for the filter row element.
238
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
239
     */
240
    public $filterRowOptions = ['class' => 'filters'];
241
    /**
242
     * @var array the options for rendering the filter error summary.
243
     * Please refer to [[Html::errorSummary()]] for more details about how to specify the options.
244
     * @see renderErrors()
245
     */
246
    public $filterErrorSummaryOptions = ['class' => 'error-summary'];
247
    /**
248
     * @var array the options for rendering every filter error message.
249
     * This is mainly used by [[Html::error()]] when rendering an error message next to every filter input field.
250
     */
251
    public $filterErrorOptions = ['class' => 'help-block'];
252
    /**
253
     * @var bool whatever to apply filters on losing focus. Leaves an ability to manage filters via yiiGridView JS
254
     * @since 2.0.16
255
     */
256
    public $filterOnFocusOut = true;
257
    /**
258
     * @var string the layout that determines how different sections of the grid view should be organized.
259
     * The following tokens will be replaced with the corresponding section contents:
260
     *
261
     * - `{summary}`: the summary section. See [[renderSummary()]].
262
     * - `{errors}`: the filter model error summary. See [[renderErrors()]].
263
     * - `{items}`: the list items. See [[renderItems()]].
264
     * - `{sorter}`: the sorter. See [[renderSorter()]].
265
     * - `{pager}`: the pager. See [[renderPager()]].
266
     */
267
    public $layout = "{summary}\n{items}\n{pager}";
268
269
270
    /**
271
     * Initializes the grid view.
272
     * This method will initialize required property values and instantiate [[columns]] objects.
273
     */
274 17
    public function init()
275
    {
276 17
        parent::init();
277 17
        if ($this->formatter === null) {
278 17
            $this->formatter = Yii::$app->getFormatter();
279
        } elseif (is_array($this->formatter)) {
280
            $this->formatter = Yii::createObject($this->formatter);
281
        }
282 17
        if (!$this->formatter instanceof Formatter) {
283
            throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
284
        }
285 17
        if (!isset($this->filterRowOptions['id'])) {
286 17
            $this->filterRowOptions['id'] = $this->options['id'] . '-filters';
287
        }
288
289 17
        $this->initColumns();
290
    }
291
292
    /**
293
     * Runs the widget.
294
     */
295 5
    public function run()
296
    {
297 5
        $view = $this->getView();
298 5
        GridViewAsset::register($view);
299 5
        $id = $this->options['id'];
300 5
        $options = Json::htmlEncode(array_merge($this->getClientOptions(), ['filterOnFocusOut' => $this->filterOnFocusOut]));
301 5
        $view->registerJs("jQuery('#$id').yiiGridView($options);");
302 5
        parent::run();
303
    }
304
305
    /**
306
     * Renders validator errors of filter model.
307
     * @return string the rendering result.
308
     */
309
    public function renderErrors()
310
    {
311
        if ($this->filterModel instanceof Model && $this->filterModel->hasErrors()) {
312
            return Html::errorSummary($this->filterModel, $this->filterErrorSummaryOptions);
313
        }
314
315
        return '';
316
    }
317
318
    /**
319
     * {@inheritdoc}
320
     */
321 5
    public function renderSection($name)
322
    {
323
        switch ($name) {
324 5
            case '{errors}':
325
                return $this->renderErrors();
326
            default:
327 5
                return parent::renderSection($name);
328
        }
329
    }
330
331
    /**
332
     * Returns the options for the grid view JS widget.
333
     * @return array the options
334
     */
335 5
    protected function getClientOptions()
336
    {
337 5
        $filterUrl = isset($this->filterUrl) ? $this->filterUrl : Yii::$app->request->url;
0 ignored issues
show
Bug Best Practice introduced by
The property url does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
338 5
        $id = $this->filterRowOptions['id'];
339 5
        $filterSelector = "#$id input, #$id select";
340 5
        if (isset($this->filterSelector)) {
341
            $filterSelector .= ', ' . $this->filterSelector;
342
        }
343
344 5
        return [
345 5
            'filterUrl' => Url::to($filterUrl),
346 5
            'filterSelector' => $filterSelector,
347 5
        ];
348
    }
349
350
    /**
351
     * Renders the data models for the grid view.
352
     * @return string the HTML code of table
353
     */
354 5
    public function renderItems()
355
    {
356 5
        $caption = $this->renderCaption();
357 5
        $columnGroup = $this->renderColumnGroup();
358 5
        $tableHeader = $this->showHeader ? $this->renderTableHeader() : false;
359 5
        $tableBody = $this->renderTableBody();
360
361 5
        $tableFooter = false;
362 5
        $tableFooterAfterBody = false;
363
364 5
        if ($this->showFooter) {
365 1
            if ($this->placeFooterAfterBody) {
366 1
                $tableFooterAfterBody = $this->renderTableFooter();
367
            } else {
368 1
                $tableFooter = $this->renderTableFooter();
369
            }
370
        }
371
372 5
        $content = array_filter([
373 5
            $caption,
374 5
            $columnGroup,
375 5
            $tableHeader,
376 5
            $tableFooter,
377 5
            $tableBody,
378 5
            $tableFooterAfterBody,
379 5
        ]);
380
381 5
        return Html::tag('table', implode("\n", $content), $this->tableOptions);
382
    }
383
384
    /**
385
     * Renders the caption element.
386
     * @return bool|string the rendered caption element or `false` if no caption element should be rendered.
387
     */
388 5
    public function renderCaption()
389
    {
390 5
        if (!empty($this->caption)) {
391
            return Html::tag('caption', $this->caption, $this->captionOptions);
392
        }
393
394 5
        return false;
395
    }
396
397
    /**
398
     * Renders the column group HTML.
399
     * @return bool|string the column group HTML or `false` if no column group should be rendered.
400
     */
401 5
    public function renderColumnGroup()
402
    {
403 5
        foreach ($this->columns as $column) {
404
            /* @var $column Column */
405 1
            if (!empty($column->options)) {
406
                $cols = [];
407
                foreach ($this->columns as $col) {
408
                    $cols[] = Html::tag('col', '', $col->options);
409
                }
410
411
                return Html::tag('colgroup', implode("\n", $cols));
412
            }
413
        }
414
415 5
        return false;
416
    }
417
418
    /**
419
     * Renders the table header.
420
     * @return string the rendering result.
421
     */
422 2
    public function renderTableHeader()
423
    {
424 2
        $cells = [];
425 2
        foreach ($this->columns as $column) {
426
            /* @var $column Column */
427 2
            $cells[] = $column->renderHeaderCell();
428
        }
429 2
        $content = Html::tag('tr', implode('', $cells), $this->headerRowOptions);
430 2
        if ($this->filterPosition === self::FILTER_POS_HEADER) {
431
            $content = $this->renderFilters() . $content;
432 2
        } elseif ($this->filterPosition === self::FILTER_POS_BODY) {
433 2
            $content .= $this->renderFilters();
434
        }
435
436 2
        return "<thead>\n" . $content . "\n</thead>";
437
    }
438
439
    /**
440
     * Renders the table footer.
441
     * @return string the rendering result.
442
     */
443 1
    public function renderTableFooter()
444
    {
445 1
        $cells = [];
446 1
        foreach ($this->columns as $column) {
447
            /* @var $column Column */
448
            $cells[] = $column->renderFooterCell();
449
        }
450 1
        $content = Html::tag('tr', implode('', $cells), $this->footerRowOptions);
451 1
        if ($this->filterPosition === self::FILTER_POS_FOOTER) {
452
            $content .= $this->renderFilters();
453
        }
454
455 1
        return "<tfoot>\n" . $content . "\n</tfoot>";
456
    }
457
458
    /**
459
     * Renders the filter.
460
     * @return string the rendering result.
461
     */
462 2
    public function renderFilters()
463
    {
464 2
        if ($this->filterModel !== null) {
465
            $cells = [];
466
            foreach ($this->columns as $column) {
467
                /* @var $column Column */
468
                $cells[] = $column->renderFilterCell();
469
            }
470
471
            return Html::tag('tr', implode('', $cells), $this->filterRowOptions);
472
        }
473
474 2
        return '';
475
    }
476
477
    /**
478
     * Renders the table body.
479
     * @return string the rendering result.
480
     */
481 5
    public function renderTableBody()
482
    {
483 5
        $models = array_values($this->dataProvider->getModels());
484 5
        $keys = $this->dataProvider->getKeys();
485 5
        $rows = [];
486 5
        foreach ($models as $index => $model) {
487 1
            $key = $keys[$index];
488 1
            if ($this->beforeRow !== null) {
489
                $row = call_user_func($this->beforeRow, $model, $key, $index, $this);
490
                if (!empty($row)) {
491
                    $rows[] = $row;
492
                }
493
            }
494
495 1
            $rows[] = $this->renderTableRow($model, $key, $index);
496
497 1
            if ($this->afterRow !== null) {
498
                $row = call_user_func($this->afterRow, $model, $key, $index, $this);
499
                if (!empty($row)) {
500
                    $rows[] = $row;
501
                }
502
            }
503
        }
504
505 5
        if (empty($rows) && $this->emptyText !== false) {
506 3
            $colspan = count($this->columns);
507
508 3
            return "<tbody>\n<tr><td colspan=\"$colspan\">" . $this->renderEmpty() . "</td></tr>\n</tbody>";
509
        }
510
511 2
        return "<tbody>\n" . implode("\n", $rows) . "\n</tbody>";
512
    }
513
514
    /**
515
     * Renders a table row with the given data model and key.
516
     * @param mixed $model the data model to be rendered
517
     * @param mixed $key the key associated with the data model
518
     * @param int $index the zero-based index of the data model among the model array returned by [[dataProvider]].
519
     * @return string the rendering result
520
     */
521 1
    public function renderTableRow($model, $key, $index)
522
    {
523 1
        $cells = [];
524
        /* @var $column Column */
525 1
        foreach ($this->columns as $column) {
526 1
            $cells[] = $column->renderDataCell($model, $key, $index);
527
        }
528 1
        if ($this->rowOptions instanceof Closure) {
529
            $options = call_user_func($this->rowOptions, $model, $key, $index, $this);
530
        } else {
531 1
            $options = $this->rowOptions;
532
        }
533 1
        $options['data-key'] = is_array($key) ? json_encode($key) : (string) $key;
534
535 1
        return Html::tag('tr', implode('', $cells), $options);
536
    }
537
538
    /**
539
     * Creates column objects and initializes them.
540
     */
541 17
    protected function initColumns()
542
    {
543 17
        if (empty($this->columns)) {
544 8
            $this->guessColumns();
545
        }
546 17
        foreach ($this->columns as $i => $column) {
547 10
            if (is_string($column)) {
548 5
                $column = $this->createDataColumn($column);
549
            } else {
550 5
                $column = Yii::createObject(array_merge([
551 5
                    'class' => $this->dataColumnClass ?: DataColumn::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

551
                    'class' => $this->dataColumnClass ?: /** @scrutinizer ignore-deprecated */ DataColumn::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
552 5
                    'grid' => $this,
553 5
                ], $column));
554
            }
555 10
            if (!$column->visible) {
556
                unset($this->columns[$i]);
557
                continue;
558
            }
559 10
            $this->columns[$i] = $column;
560
        }
561
    }
562
563
    /**
564
     * Creates a [[DataColumn]] object based on a string in the format of "attribute:format:label".
565
     * @param string $text the column specification string
566
     * @return DataColumn the column instance
567
     * @throws InvalidConfigException if the column specification is invalid
568
     */
569 5
    protected function createDataColumn($text)
570
    {
571 5
        if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $text, $matches)) {
572
            throw new InvalidConfigException('The column must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
573
        }
574
575 5
        return Yii::createObject([
576 5
            'class' => $this->dataColumnClass ?: DataColumn::className(),
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

576
            'class' => $this->dataColumnClass ?: /** @scrutinizer ignore-deprecated */ DataColumn::className(),

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
577 5
            'grid' => $this,
578 5
            'attribute' => $matches[1],
579 5
            'format' => isset($matches[3]) ? $matches[3] : 'text',
580 5
            'label' => isset($matches[5]) ? $matches[5] : null,
581 5
        ]);
582
    }
583
584
    /**
585
     * This function tries to guess the columns to show from the given data
586
     * if [[columns]] are not explicitly specified.
587
     */
588 8
    protected function guessColumns()
589
    {
590 8
        $models = $this->dataProvider->getModels();
591 8
        $model = reset($models);
592 8
        if (is_array($model) || is_object($model)) {
593 1
            foreach ($model as $name => $value) {
594 1
                if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) {
595 1
                    $this->columns[] = (string) $name;
596
                }
597
            }
598
        }
599
    }
600
}
601