Completed
Push — master ( 483e09...987c30 )
by Dmitry
11:33 queued 05:11
created

DetailView   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 183
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 71.79%

Importance

Changes 0
Metric Value
wmc 31
lcom 1
cbo 8
dl 0
loc 183
ccs 56
cts 78
cp 0.7179
rs 9.8
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
B init() 0 19 6
A run() 0 12 2
A renderAttribute() 0 15 2
D normalizeAttributes() 0 54 21
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\widgets;
9
10
use Yii;
11
use yii\base\Arrayable;
12
use yii\i18n\Formatter;
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
20
/**
21
 * DetailView displays the detail of a single data [[model]].
22
 *
23
 * DetailView is best used for displaying a model in a regular format (e.g. each model attribute
24
 * is displayed as a row in a table.) The model can be either an instance of [[Model]]
25
 * or an associative array.
26
 *
27
 * DetailView uses the [[attributes]] property to determines which model attributes
28
 * should be displayed and how they should be formatted.
29
 *
30
 * A typical usage of DetailView is as follows:
31
 *
32
 * ```php
33
 * echo DetailView::widget([
34
 *     'model' => $model,
35
 *     'attributes' => [
36
 *         'title',               // title attribute (in plain text)
37
 *         'description:html',    // description attribute in HTML
38
 *         [                      // the owner name of the model
39
 *             'label' => 'Owner',
40
 *             'value' => $model->owner->name,
41
 *         ],
42
 *         'created_at:datetime', // creation date formatted as datetime
43
 *     ],
44
 * ]);
45
 * ```
46
 *
47
 * @author Qiang Xue <[email protected]>
48
 * @since 2.0
49
 */
50
class DetailView extends Widget
51
{
52
    /**
53
     * @var array|object the data model whose details are to be displayed. This can be a [[Model]] instance,
54
     * an associative array, an object that implements [[Arrayable]] interface or simply an object with defined
55
     * public accessible non-static properties.
56
     */
57
    public $model;
58
    /**
59
     * @var array a list of attributes to be displayed in the detail view. Each array element
60
     * represents the specification for displaying one particular attribute.
61
     *
62
     * An attribute can be specified as a string in the format of "attribute", "attribute:format" or "attribute:format:label",
63
     * where "attribute" refers to the attribute name, and "format" represents the format of the attribute. The "format"
64
     * is passed to the [[Formatter::format()]] method to format an attribute value into a displayable text.
65
     * Please refer to [[Formatter]] for the supported types. Both "format" and "label" are optional.
66
     * They will take default values if absent.
67
     *
68
     * An attribute can also be specified in terms of an array with the following elements:
69
     *
70
     * - attribute: the attribute name. This is required if either "label" or "value" is not specified.
71
     * - label: the label associated with the attribute. If this is not specified, it will be generated from the attribute name.
72
     * - value: the value to be displayed. If this is not specified, it will be retrieved from [[model]] using the attribute name
73
     *   by calling [[ArrayHelper::getValue()]]. Note that this value will be formatted into a displayable text
74
     *   according to the "format" option.
75
     * - format: the type of the value that determines how the value would be formatted into a displayable text.
76
     *   Please refer to [[Formatter]] for supported types.
77
     * - visible: whether the attribute is visible. If set to `false`, the attribute will NOT be displayed.
78
     * - contentOptions: the HTML attributes to customize value tag. For example: `['class' => 'bg-red']`.
79
     *   Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
80
     * - captionOptions: the HTML attributes to customize label tag. For example: `['class' => 'bg-red']`.
81
     *   Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
82
     */
83
    public $attributes;
84
    /**
85
     * @var string|callable the template used to render a single attribute. If a string, the token `{label}`
86
     * and `{value}` will be replaced with the label and the value of the corresponding attribute.
87
     * If a callback (e.g. an anonymous function), the signature must be as follows:
88
     *
89
     * ```php
90
     * function ($attribute, $index, $widget)
91
     * ```
92
     *
93
     * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
94
     * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
95
     */
96
    public $template = '<tr><th{captionOptions}>{label}</th><td{contentOptions}>{value}</td></tr>';
97
    /**
98
     * @var array the HTML attributes for the container tag of this widget. The "tag" option specifies
99
     * what container tag should be used. It defaults to "table" if not set.
100
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
101
     */
102
    public $options = ['class' => 'table table-striped table-bordered detail-view'];
103
    /**
104
     * @var array|Formatter the formatter used to format model attribute values into displayable texts.
105
     * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
106
     * instance. If this property is not set, the "formatter" application component will be used.
107
     */
108
    public $formatter;
109
110
111
    /**
112
     * Initializes the detail view.
113
     * This method will initialize required property values.
114
     */
115 5
    public function init()
116
    {
117 5
        if ($this->model === null) {
118
            throw new InvalidConfigException('Please specify the "model" property.');
119
        }
120 5
        if ($this->formatter === null) {
121 5
            $this->formatter = Yii::$app->getFormatter();
122 5
        } elseif (is_array($this->formatter)) {
123
            $this->formatter = Yii::createObject($this->formatter);
124
        }
125 5
        if (!$this->formatter instanceof Formatter) {
126
            throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
127
        }
128 5
        $this->normalizeAttributes();
129
130 5
        if (!isset($this->options['id'])) {
131 5
            $this->options['id'] = $this->getId();
132 5
        }
133 5
    }
134
135
    /**
136
     * Renders the detail view.
137
     * This is the main entry of the whole detail view rendering.
138
     */
139
    public function run()
140
    {
141
        $rows = [];
142
        $i = 0;
143
        foreach ($this->attributes as $attribute) {
144
            $rows[] = $this->renderAttribute($attribute, $i++);
145
        }
146
147
        $options = $this->options;
148
        $tag = ArrayHelper::remove($options, 'tag', 'table');
149
        echo Html::tag($tag, implode("\n", $rows), $options);
150
    }
151
152
    /**
153
     * Renders a single attribute.
154
     * @param array $attribute the specification of the attribute to be rendered.
155
     * @param integer $index the zero-based index of the attribute in the [[attributes]] array
156
     * @return string the rendering result
157
     */
158 2
    protected function renderAttribute($attribute, $index)
159
    {
160 2
        if (is_string($this->template)) {
161 2
            $captionOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'captionOptions', []));
162 2
            $contentOptions = Html::renderTagAttributes(ArrayHelper::getValue($attribute, 'contentOptions', []));
163 2
            return strtr($this->template, [
164 2
                '{label}' => $attribute['label'],
165 2
                '{value}' => $this->formatter->format($attribute['value'], $attribute['format']),
166 2
                '{captionOptions}' => $captionOptions,
167 2
                '{contentOptions}' =>  $contentOptions,
168 2
            ]);
169
        } else {
170
            return call_user_func($this->template, $attribute, $index, $this);
171
        }
172
    }
173
174
    /**
175
     * Normalizes the attribute specifications.
176
     * @throws InvalidConfigException
177
     */
178 5
    protected function normalizeAttributes()
179
    {
180 5
        if ($this->attributes === null) {
181 3
            if ($this->model instanceof Model) {
182
                $this->attributes = $this->model->attributes();
183 3
            } elseif (is_object($this->model)) {
184 2
                $this->attributes = $this->model instanceof Arrayable ? array_keys($this->model->toArray()) : array_keys(get_object_vars($this->model));
185 3
            } elseif (is_array($this->model)) {
186 1
                $this->attributes = array_keys($this->model);
187 1
            } else {
188
                throw new InvalidConfigException('The "model" property must be either an array or an object.');
189
            }
190 3
            sort($this->attributes);
191 3
        }
192
193 5
        foreach ($this->attributes as $i => $attribute) {
194 5
            if (is_string($attribute)) {
195 4
                if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $attribute, $matches)) {
196
                    throw new InvalidConfigException('The attribute must be specified in the format of "attribute", "attribute:format" or "attribute:format:label"');
197
                }
198
                $attribute = [
199 4
                    'attribute' => $matches[1],
200 4
                    'format' => isset($matches[3]) ? $matches[3] : 'text',
201 4
                    'label' => isset($matches[5]) ? $matches[5] : null,
202 4
                ];
203 4
            }
204
205 5
            if (!is_array($attribute)) {
206
                throw new InvalidConfigException('The attribute configuration must be an array.');
207
            }
208
209 5
            if (isset($attribute['visible']) && !$attribute['visible']) {
210
                unset($this->attributes[$i]);
211
                continue;
212
            }
213
214 5
            if (!isset($attribute['format'])) {
215 1
                $attribute['format'] = 'text';
216 1
            }
217 5
            if (isset($attribute['attribute'])) {
218 5
                $attributeName = $attribute['attribute'];
219 5
                if (!isset($attribute['label'])) {
220 4
                    $attribute['label'] = $this->model instanceof Model ? $this->model->getAttributeLabel($attributeName) : Inflector::camel2words($attributeName, true);
221 4
                }
222 5
                if (!array_key_exists('value', $attribute)) {
223 5
                    $attribute['value'] = ArrayHelper::getValue($this->model, $attributeName);
224 5
                }
225 5
            } elseif (!isset($attribute['label']) || !array_key_exists('value', $attribute)) {
226
                throw new InvalidConfigException('The attribute configuration requires the "attribute" element to determine the value and display label.');
227
            }
228
229 5
            $this->attributes[$i] = $attribute;
230 5
        }
231 5
    }
232
}
233