Passed
Pull Request — 2.2 (#20357)
by Wilmer
08:02 queued 17s
created

DataColumn::renderFilterCellContent()   B

Complexity

Conditions 9
Paths 8

Size

Total Lines 31
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 9.2363

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 21
c 1
b 0
f 0
nc 8
nop 0
dl 0
loc 31
ccs 18
cts 21
cp 0.8571
crap 9.2363
rs 8.0555
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\base\Model;
13
use yii\data\ActiveDataProvider;
14
use yii\data\ArrayDataProvider;
15
use yii\db\ActiveQueryInterface;
16
use yii\helpers\ArrayHelper;
17
use yii\helpers\Html;
18
use yii\helpers\Inflector;
19
20
/**
21
 * DataColumn is the default column type for the [[GridView]] widget.
22
 *
23
 * It is used to show data columns and allows [[enableSorting|sorting]] and [[filter|filtering]] them.
24
 *
25
 * A simple data column definition refers to an attribute in the data model of the
26
 * GridView's data provider. The name of the attribute is specified by [[attribute]].
27
 *
28
 * By setting [[value]] and [[label]], the header and cell content can be customized.
29
 *
30
 * A data column differentiates between the [[getDataCellValue|data cell value]] and the
31
 * [[renderDataCellContent|data cell content]]. The cell value is an un-formatted value that
32
 * may be used for calculation, while the actual cell content is a [[format|formatted]] version of that
33
 * value which may contain HTML markup.
34
 *
35
 * For more details and usage information on DataColumn, see the [guide article on data widgets](guide:output-data-widgets).
36
 *
37
 * @author Qiang Xue <[email protected]>
38
 * @since 2.0
39
 */
40
class DataColumn extends Column
41
{
42
    /**
43
     * @var string the attribute name associated with this column. When neither [[content]] nor [[value]]
44
     * is specified, the value of the specified attribute will be retrieved from each data model and displayed.
45
     *
46
     * Also, if [[label]] is not specified, the label associated with the attribute will be displayed.
47
     */
48
    public $attribute;
49
    /**
50
     * @var string|null label to be displayed in the [[header|header cell]] and also to be used as the sorting
51
     * link label when sorting is enabled for this column.
52
     * If it is not set and the models provided by the GridViews data provider are instances
53
     * of [[\yii\db\ActiveRecord]], the label will be determined using [[\yii\db\ActiveRecord::getAttributeLabel()]].
54
     * Otherwise [[\yii\helpers\Inflector::camel2words()]] will be used to get a label.
55
     */
56
    public $label;
57
    /**
58
     * @var bool whether the header label should be HTML-encoded.
59
     * @see label
60
     * @since 2.0.1
61
     */
62
    public $encodeLabel = true;
63
    /**
64
     * @var string|Closure|null an anonymous function or a string that is used to determine the value to display in the current column.
65
     *
66
     * If this is an anonymous function, it will be called for each row and the return value will be used as the value to
67
     * display for every data model. The signature of this function should be: `function ($model, $key, $index, $column)`.
68
     * Where `$model`, `$key`, and `$index` refer to the model, key and index of the row currently being rendered
69
     * and `$column` is a reference to the [[DataColumn]] object.
70
     *
71
     * You may also set this property to a string representing the attribute name to be displayed in this column.
72
     * This can be used when the attribute to be displayed is different from the [[attribute]] that is used for
73
     * sorting and filtering.
74
     *
75
     * If this is not set, `$model[$attribute]` will be used to obtain the value, where `$attribute` is the value of [[attribute]].
76
     */
77
    public $value;
78
    /**
79
     * @var string|array|Closure in which format should the value of each data model be displayed as (e.g. `"raw"`, `"text"`, `"html"`,
80
     * `['date', 'php:Y-m-d']`). Supported formats are determined by the [[GridView::formatter|formatter]] used by
81
     * the [[GridView]]. Default format is "text" which will format the value as an HTML-encoded plain text when
82
     * [[\yii\i18n\Formatter]] is used as the [[GridView::$formatter|formatter]] of the GridView.
83
     * @see \yii\i18n\Formatter::format()
84
     */
85
    public $format = 'text';
86
    /**
87
     * @var bool whether to allow sorting by this column. If true and [[attribute]] is found in
88
     * the sort definition of [[GridView::dataProvider]], then the header cell of this column
89
     * will contain a link that may trigger the sorting when being clicked.
90
     */
91
    public $enableSorting = true;
92
    /**
93
     * @var array the HTML attributes for the link tag in the header cell
94
     * generated by [[\yii\data\Sort::link]] when sorting is enabled for this column.
95
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
96
     */
97
    public $sortLinkOptions = [];
98
    /**
99
     * @var string|array|null|false the HTML code representing a filter input (e.g. a text field, a dropdown list)
100
     * that is used for this data column. This property is effective only when [[GridView::filterModel]] is set.
101
     *
102
     * - If this property is not set, a text field will be generated as the filter input with attributes defined
103
     *   with [[filterInputOptions]]. See [[\yii\helpers\BaseHtml::activeInput]] for details on how an active
104
     *   input tag is generated.
105
     * - If this property is an array, a dropdown list will be generated that uses this property value as
106
     *   the list options.
107
     * - If you don't want a filter for this data column, set this value to be false.
108
     */
109
    public $filter;
110
    /**
111
     * @var array the HTML attributes for the filter input fields. This property is used in combination with
112
     * the [[filter]] property. When [[filter]] is not set or is an array, this property will be used to
113
     * render the HTML attributes for the generated filter input fields.
114
     *
115
     * Empty `id` in the default value ensures that id would not be obtained from the model attribute thus
116
     * providing better performance.
117
     *
118
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
119
     */
120
    public $filterInputOptions = ['class' => 'form-control', 'id' => null];
121
    /**
122
     * @var string|null the attribute name of the [[GridView::filterModel]] associated with this column. If not set,
123
     * will have the same value as [[attribute]].
124
     * @since 2.0.41
125
     */
126
    public $filterAttribute;
127
128
129
    /**
130
     * {@inheritdoc}
131
     */
132 8
    public function init()
133
    {
134 8
        parent::init();
135 8
        if ($this->filterAttribute === null) {
136 7
            $this->filterAttribute = $this->attribute;
137
        }
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143
    protected function renderHeaderCellContent()
144
    {
145
        if ($this->header !== null || $this->label === null && $this->attribute === null) {
146
            return parent::renderHeaderCellContent();
147
        }
148
149
        $label = $this->getHeaderCellLabel();
150
        if ($this->encodeLabel) {
151
            $label = Html::encode($label);
152
        }
153
154
        if (
155
            $this->attribute !== null && $this->enableSorting &&
156
            ($sort = $this->grid->dataProvider->getSort()) !== false && $sort->hasAttribute($this->attribute)
157
        ) {
158
            return $sort->link($this->attribute, array_merge($this->sortLinkOptions, ['label' => $label]));
159
        }
160
161
        return $label;
162
    }
163
164
    /**
165
     * {@inheritdoc}
166
     * @since 2.0.8
167
     */
168 2
    protected function getHeaderCellLabel()
169
    {
170 2
        $provider = $this->grid->dataProvider;
171
172 2
        if ($this->label === null) {
173 2
            if ($this->attribute === null) {
174
                $label = '';
175 2
            } elseif ($provider instanceof ActiveDataProvider && $provider->query instanceof ActiveQueryInterface) {
176
                /* @var $modelClass Model */
177
                $modelClass = $provider->query->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
178
                $model = $modelClass::instance();
179
                $label = $model->getAttributeLabel($this->attribute);
180 2
            } elseif ($provider instanceof ArrayDataProvider && $provider->modelClass !== null) {
181
                /* @var $modelClass Model */
182 1
                $modelClass = $provider->modelClass;
183 1
                $model = $modelClass::instance();
184 1
                $label = $model->getAttributeLabel($this->attribute);
185 1
            } elseif ($this->grid->filterModel !== null && $this->grid->filterModel instanceof Model) {
186 1
                $label = $this->grid->filterModel->getAttributeLabel($this->filterAttribute);
187
            } else {
188
                $models = $provider->getModels();
189
                if (($model = reset($models)) instanceof Model) {
190
                    /* @var $model Model */
191
                    $label = $model->getAttributeLabel($this->attribute);
192
                } else {
193 2
                    $label = Inflector::camel2words($this->attribute);
194
                }
195
            }
196
        } else {
197
            $label = $this->label;
198
        }
199
200 2
        return $label;
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206 5
    protected function renderFilterCellContent()
207
    {
208 5
        if (is_string($this->filter)) {
209 1
            return $this->filter;
210
        }
211
212 4
        $model = $this->grid->filterModel;
213
214 4
        if ($this->filter !== false && $model instanceof Model && $this->filterAttribute !== null && $model->isAttributeActive($this->filterAttribute)) {
215 4
            if ($model->hasErrors($this->filterAttribute)) {
216
                Html::addCssClass($this->filterOptions, 'has-error');
217
                $error = ' ' . Html::error($model, $this->filterAttribute, $this->grid->filterErrorOptions);
218
            } else {
219 4
                $error = '';
220
            }
221 4
            if (is_array($this->filter)) {
222 1
                $options = array_merge(['prompt' => '', 'strict' => true], $this->filterInputOptions);
223 1
                return Html::activeDropDownList($model, $this->filterAttribute, $this->filter, $options) . $error;
224 3
            } elseif ($this->format === 'boolean') {
225 1
                $options = array_merge(['prompt' => '', 'strict' => true], $this->filterInputOptions);
226 1
                return Html::activeDropDownList($model, $this->filterAttribute, [
227 1
                    1 => $this->grid->formatter->booleanFormat[1],
228 1
                    0 => $this->grid->formatter->booleanFormat[0],
229 1
                ], $options) . $error;
230
            }
231 2
            $options = array_merge(['maxlength' => true], $this->filterInputOptions);
232
233 2
            return Html::activeTextInput($model, $this->filterAttribute, $options) . $error;
234
        }
235
236
        return parent::renderFilterCellContent();
237
    }
238
239
    /**
240
     * Returns the data cell value.
241
     * @param mixed $model the data model
242
     * @param mixed $key the key associated with the data model
243
     * @param int $index the zero-based index of the data model among the models array returned by [[GridView::dataProvider]].
244
     * @return string the data cell value
245
     */
246
    public function getDataCellValue($model, $key, $index)
247
    {
248
        if ($this->value !== null) {
249
            if (is_string($this->value)) {
250
                return ArrayHelper::getValue($model, $this->value);
251
            }
252
253
            return call_user_func($this->value, $model, $key, $index, $this);
254
        } elseif ($this->attribute !== null) {
255
            return ArrayHelper::getValue($model, $this->attribute);
256
        }
257
258
        return null;
259
    }
260
261
    /**
262
     * {@inheritdoc}
263
     */
264
    protected function renderDataCellContent($model, $key, $index)
265
    {
266
        if ($this->content === null) {
267
            return $this->grid->formatter->format($this->getDataCellValue($model, $key, $index), $this->format);
0 ignored issues
show
Bug introduced by
The method format() does not exist on null. ( Ignorable by Annotation )

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

267
            return $this->grid->formatter->/** @scrutinizer ignore-call */ format($this->getDataCellValue($model, $key, $index), $this->format);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
268
        }
269
270
        return parent::renderDataCellContent($model, $key, $index);
271
    }
272
}
273