Completed
Push — remove-intl-polyfills ( 129df4...a6e727 )
by Alexander
16:22 queued 12:49
created

DetailView::renderAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 2.004

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 10
nc 2
nop 2
crap 2.004
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\base\InvalidConfigException;
13
use yii\base\Model;
14
use yii\base\Widget;
15
use yii\helpers\ArrayHelper;
16
use yii\helpers\Html;
17
use yii\helpers\Inflector;
18
use yii\i18n\Formatter;
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
 * For more details and usage information on DetailView, see the [guide article on data widgets](guide:output-data-widgets).
48
 *
49
 * @author Qiang Xue <[email protected]>
50
 * @since 2.0
51
 */
52
class DetailView extends Widget
53
{
54
    /**
55
     * @var array|object the data model whose details are to be displayed. This can be a [[Model]] instance,
56
     * an associative array, an object that implements [[Arrayable]] interface or simply an object with defined
57
     * public accessible non-static properties.
58
     */
59
    public $model;
60
    /**
61
     * @var array a list of attributes to be displayed in the detail view. Each array element
62
     * represents the specification for displaying one particular attribute.
63
     *
64
     * An attribute can be specified as a string in the format of `attribute`, `attribute:format` or `attribute:format:label`,
65
     * where `attribute` refers to the attribute name, and `format` represents the format of the attribute. The `format`
66
     * is passed to the [[Formatter::format()]] method to format an attribute value into a displayable text.
67
     * Please refer to [[Formatter]] for the supported types. Both `format` and `label` are optional.
68
     * They will take default values if absent.
69
     *
70
     * An attribute can also be specified in terms of an array with the following elements:
71
     *
72
     * - `attribute`: the attribute name. This is required if either `label` or `value` is not specified.
73
     * - `label`: the label associated with the attribute. If this is not specified, it will be generated from the attribute name.
74
     * - `value`: the value to be displayed. If this is not specified, it will be retrieved from [[model]] using the attribute name
75
     *   by calling [[ArrayHelper::getValue()]]. Note that this value will be formatted into a displayable text
76
     *   according to the `format` option. Since version 2.0.11 it can be defined as closure with the following
77
     *   parameters:
78
     *
79
     *   ```php
80
     *   function ($model, $widget)
81
     *   ```
82
     *
83
     *   `$model` refers to displayed model and `$widget` is an instance of `DetailView` widget.
84
     *
85
     * - `format`: the type of the value that determines how the value would be formatted into a displayable text.
86
     *   Please refer to [[Formatter]] for supported types and [[Formatter::format()]] on how to specify this value.
87
     * - `visible`: whether the attribute is visible. If set to `false`, the attribute will NOT be displayed.
88
     * - `contentOptions`: the HTML attributes to customize value tag. For example: `['class' => 'bg-red']`.
89
     *   Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
90
     * - `captionOptions`: the HTML attributes to customize label tag. For example: `['class' => 'bg-red']`.
91
     *   Please refer to [[\yii\helpers\BaseHtml::renderTagAttributes()]] for the supported syntax.
92
     */
93
    public $attributes;
94
    /**
95
     * @var string|callable the template used to render a single attribute. If a string, the token `{label}`
96
     * and `{value}` will be replaced with the label and the value of the corresponding attribute.
97
     * If a callback (e.g. an anonymous function), the signature must be as follows:
98
     *
99
     * ```php
100
     * function ($attribute, $index, $widget)
101
     * ```
102
     *
103
     * where `$attribute` refer to the specification of the attribute being rendered, `$index` is the zero-based
104
     * index of the attribute in the [[attributes]] array, and `$widget` refers to this widget instance.
105
     *
106
     * Since Version 2.0.10, the tokens `{captionOptions}` and `{contentOptions}` are available, which will represent
107
     * HTML attributes of HTML container elements for the label and value.
108
     */
109
    public $template = '<tr><th{captionOptions}>{label}</th><td{contentOptions}>{value}</td></tr>';
110
    /**
111
     * @var array the HTML attributes for the container tag of this widget. The `tag` option specifies
112
     * what container tag should be used. It defaults to `table` if not set.
113
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
114
     */
115
    public $options = ['class' => 'table table-striped table-bordered detail-view'];
116
    /**
117
     * @var array|Formatter the formatter used to format model attribute values into displayable texts.
118
     * This can be either an instance of [[Formatter]] or an configuration array for creating the [[Formatter]]
119
     * instance. If this property is not set, the `formatter` application component will be used.
120
     */
121
    public $formatter;
122
123
124
    /**
125
     * Initializes the detail view.
126
     * This method will initialize required property values.
127
     */
128 9
    public function init()
129
    {
130 9
        parent::init();
131
132 9
        if ($this->model === null) {
133
            throw new InvalidConfigException('Please specify the "model" property.');
134
        }
135 9
        if ($this->formatter === null) {
136 9
            $this->formatter = Yii::$app->getFormatter();
137
        } elseif (is_array($this->formatter)) {
138
            $this->formatter = Yii::createObject($this->formatter);
139
        }
140 9
        if (!$this->formatter instanceof Formatter) {
141
            throw new InvalidConfigException('The "formatter" property must be either a Format object or a configuration array.');
142
        }
143 9
        $this->normalizeAttributes();
144
145 9
        if (!isset($this->options['id'])) {
146 9
            $this->options['id'] = $this->getId();
147
        }
148 9
    }
149
150
    /**
151
     * Renders the detail view.
152
     * This is the main entry of the whole detail view rendering.
153
     * @return string the result of widget execution to be outputted.
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
        return 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']),
182 4
                '{captionOptions}' => $captionOptions,
183 4
                '{contentOptions}' => $contentOptions,
184
            ]);
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)) {
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
                $attribute = [
215 7
                    'attribute' => $matches[1],
216 7
                    'format' => $matches[3] ?? 'text',
217 7
                    'label' => $matches[5] ?? null,
218
                ];
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 9
    }
252
}
253