DetailView::normalizeAttributes()   F
last analyzed

Complexity

Conditions 22
Paths 811

Size

Total Lines 56
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 23.1934

Importance

Changes 0
Metric Value
cc 22
eloc 36
nc 811
nop 0
dl 0
loc 56
ccs 32
cts 37
cp 0.8649
crap 23.1934
rs 0.2624
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\widgets;
10
11
use Yii;
12
use yii\base\Arrayable;
13
use yii\base\InvalidConfigException;
14
use yii\base\Model;
15
use yii\base\Widget;
16
use yii\helpers\ArrayHelper;
17
use yii\helpers\Html;
18
use yii\helpers\Inflector;
19
use yii\i18n\Formatter;
20
21
/**
22
 * DetailView displays the detail of a single data [[model]].
23
 *
24
 * DetailView is best used for displaying a model in a regular format (e.g. each model attribute
25
 * is displayed as a row in a table.) The model can be either an instance of [[Model]]
26
 * or an associative array.
27
 *
28
 * DetailView uses the [[attributes]] property to determines which model attributes
29
 * should be displayed and how they should be formatted.
30
 *
31
 * A typical usage of DetailView is as follows:
32
 *
33
 * ```php
34
 * echo DetailView::widget([
35
 *     'model' => $model,
36
 *     'attributes' => [
37
 *         'title',               // title attribute (in plain text)
38
 *         'description:html',    // description attribute in HTML
39
 *         [                      // the owner name of the model
40
 *             'label' => 'Owner',
41
 *             'value' => $model->owner->name,
42
 *         ],
43
 *         'created_at:datetime', // creation date formatted as datetime
44
 *     ],
45
 * ]);
46
 * ```
47
 *
48
 * For more details and usage information on DetailView, see the [guide article on data widgets](guide:output-data-widgets).
49
 *
50
 * @author Qiang Xue <[email protected]>
51
 * @since 2.0
52
 */
53
class DetailView extends Widget
54
{
55
    /**
56
     * @var array|object the data model whose details are to be displayed. This can be a [[Model]] instance,
57
     * an associative array, an object that implements [[Arrayable]] interface or simply an object with defined
58
     * public accessible non-static properties.
59
     */
60
    public $model;
61
    /**
62
     * @var array a list of attributes to be displayed in the detail view. Each array element
63
     * represents the specification for displaying one particular attribute.
64
     *
65
     * An attribute can be specified as a string in the format of `attribute`, `attribute:format` or `attribute:format:label`,
66
     * where `attribute` refers to the attribute name, and `format` represents the format of the attribute. The `format`
67
     * is passed to the [[Formatter::format()]] method to format an attribute value into a displayable text.
68
     * Please refer to [[Formatter]] for the supported types. Both `format` and `label` are optional.
69
     * They will take default values if absent.
70
     *
71
     * An attribute can also be specified in terms of an array with the following elements:
72
     *
73
     * - `attribute`: the attribute name. This is required if either `label` or `value` is not specified.
74
     * - `label`: the label associated with the attribute. If this is not specified, it will be generated from the attribute name.
75
     * - `value`: the value to be displayed. If this is not specified, it will be retrieved from [[model]] using the attribute name
76
     *   by calling [[ArrayHelper::getValue()]]. Note that this value will be formatted into a displayable text
77
     *   according to the `format` option. Since version 2.0.11 it can be defined as closure with the following
78
     *   parameters:
79
     *
80
     *   ```php
81
     *   function ($model, $widget)
82
     *   ```
83
     *
84
     *   `$model` refers to displayed model and `$widget` is an instance of `DetailView` widget.
85
     *
86
     * - `format`: the type of the value that determines how the value would be formatted into a displayable text.
87
     *   Please refer to [[Formatter]] for supported types and [[Formatter::format()]] on how to specify this value.
88
     * - `visible`: whether the attribute is visible. If set to `false`, the attribute will NOT be displayed.
89
     * - `contentOptions`: the HTML attributes to customize value tag. For example: `['class' => 'bg-red']`.
90
     *   Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
91
     * - `captionOptions`: the HTML attributes to customize label tag. For example: `['class' => 'bg-red']`.
92
     *   Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
93
     */
94
    public $attributes;
95
    /**
96
     * @var string|callable the template used to render a single attribute. If a string, the token `{label}`
97
     * and `{value}` will be replaced with the label and the value of the corresponding attribute.
98
     * If a callback (e.g. an anonymous function), the signature must be as follows:
99
     *
100
     * ```php
101
     * function ($attribute, $index, $widget)
102
     * ```
103
     *
104
     * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
105
     * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
106
     *
107
     * Since Version 2.0.10, the tokens `{captionOptions}` and `{contentOptions}` are available, which will represent
108
     * HTML attributes of HTML container elements for the label and value.
109
     */
110
    public $template = '<tr><th{captionOptions}>{label}</th><td{contentOptions}>{value}</td></tr>';
111
    /**
112
     * @var array|null the HTML attributes for the container tag of this widget. The `tag` option specifies
113
     * what container tag should be used. It defaults to `table` if not set.
114
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
115
     */
116
    public $options = ['class' => 'table table-striped table-bordered detail-view'];
117
    /**
118
     * @var array|Formatter|null the formatter used to format model attribute values into displayable texts.
119
     * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
120
     * instance. If this property is not set, the `formatter` application component will be used.
121
     */
122
    public $formatter;
123
124
125
    /**
126
     * Initializes the detail view.
127
     * This method will initialize required property values.
128
     */
129 9
    public function init()
130
    {
131 9
        parent::init();
132
133 9
        if ($this->model === null) {
134
            throw new InvalidConfigException('Please specify the "model" property.');
135
        }
136 9
        if ($this->formatter === null) {
137 9
            $this->formatter = Yii::$app->getFormatter();
138
        } elseif (is_array($this->formatter)) {
139
            $this->formatter = Yii::createObject($this->formatter);
140
        }
141 9
        if (!$this->formatter instanceof Formatter) {
142
            throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
143
        }
144 9
        $this->normalizeAttributes();
145
146 9
        if (!isset($this->options['id'])) {
147 9
            $this->options['id'] = $this->getId();
148
        }
149
    }
150
151
    /**
152
     * Renders the detail view.
153
     * This is the main entry of the whole detail view rendering.
154
     */
155
    public function run()
156
    {
157
        $rows = [];
158
        $i = 0;
159
        foreach ($this->attributes as $attribute) {
160
            $rows[] = $this->renderAttribute($attribute, $i++);
161
        }
162
163
        $options = $this->options;
164
        $tag = ArrayHelper::remove($options, 'tag', 'table');
165
        echo Html::tag($tag, implode("\n", $rows), $options);
166
    }
167
168
    /**
169
     * Renders a single attribute.
170
     * @param array $attribute the specification of the attribute to be rendered.
171
     * @param int $index the zero-based index of the attribute in the [[attributes]] array
172
     * @return string the rendering result
173
     */
174 4
    protected function renderAttribute($attribute, $index)
175
    {
176 4
        if (is_string($this->template)) {
177 4
            $captionOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'captionOptions', []));
178 4
            $contentOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'contentOptions', []));
179 4
            return strtr($this->template, [
180 4
                '{label}' => $attribute['label'],
181 4
                '{value}' => $this->formatter->format($attribute['value'], $attribute['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

181
                '{value}' => $this->formatter->/** @scrutinizer ignore-call */ format($attribute['value'], $attribute['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...
182 4
                '{captionOptions}' => $captionOptions,
183 4
                '{contentOptions}' => $contentOptions,
184 4
            ]);
185
        }
186
187
        return call_user_func($this->template, $attribute, $index, $this);
188
    }
189
190
    /**
191
     * Normalizes the attribute specifications.
192
     * @throws InvalidConfigException
193
     */
194 9
    protected function normalizeAttributes()
195
    {
196 9
        if ($this->attributes === null) {
197 4
            if ($this->model instanceof Model) {
198 2
                $this->attributes = $this->model->attributes();
199 2
            } elseif (is_object($this->model)) {
200 1
                $this->attributes = $this->model instanceof Arrayable ? array_keys($this->model->toArray()) : array_keys(get_object_vars($this->model));
201 1
            } elseif (is_array($this->model)) {
0 ignored issues
show
introduced by
The condition is_array($this->model) is always true.
Loading history...
202 1
                $this->attributes = array_keys($this->model);
203
            } else {
204
                throw new InvalidConfigException('The "model" property must be either an array or an object.');
205
            }
206 4
            sort($this->attributes);
207
        }
208
209 9
        foreach ($this->attributes as $i => $attribute) {
210 9
            if (is_string($attribute)) {
211 7
                if (!preg_match('/^([^:]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) {
212
                    throw new InvalidConfigException('The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
213
                }
214 7
                $attribute = [
215 7
                    'attribute' => $matches[1],
216 7
                    'format' => isset($matches[3]) ? $matches[3] : 'text',
217 7
                    'label' => isset($matches[5]) ? $matches[5] : null,
218 7
                ];
219
            }
220
221 9
            if (!is_array($attribute)) {
222
                throw new InvalidConfigException('The attribute configuration must be an array.');
223
            }
224
225 9
            if (isset($attribute['visible']) && !$attribute['visible']) {
226 1
                unset($this->attributes[$i]);
227 1
                continue;
228
            }
229
230 9
            if (!isset($attribute['format'])) {
231 3
                $attribute['format'] = 'text';
232
            }
233 9
            if (isset($attribute['attribute'])) {
234 9
                $attributeName = $attribute['attribute'];
235 9
                if (!isset($attribute['label'])) {
236 8
                    $attribute['label'] = $this->model instanceof Model ? $this->model->getAttributeLabel($attributeName) : Inflector::camel2words($attributeName, true);
237
                }
238 9
                if (!array_key_exists('value', $attribute)) {
239 9
                    $attribute['value'] = ArrayHelper::getValue($this->model, $attributeName);
240
                }
241
            } elseif (!isset($attribute['label']) || !array_key_exists('value', $attribute)) {
242
                throw new InvalidConfigException('The attribute configuration requires the "attribute" element to determine the value and display label.');
243
            }
244
245 9
            if ($attribute['value'] instanceof \Closure) {
246 2
                $attribute['value'] = call_user_func($attribute['value'], $this->model, $this);
247
            }
248
249 9
            $this->attributes[$i] = $attribute;
250
        }
251
    }
252
}
253