Completed
Push — master ( 625d55...2d12e1 )
by Carsten
12:37
created

BaseListView::renderSection()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 9
cts 10
cp 0.9
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 12
nc 5
nop 1
crap 5.025
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\InvalidConfigException;
12
use yii\base\Widget;
13
use yii\helpers\ArrayHelper;
14
use yii\helpers\Html;
15
16
/**
17
 * BaseListView is a base class for widgets displaying data from data provider
18
 * such as ListView and GridView.
19
 *
20
 * It provides features like sorting, paging and also filtering the data.
21
 *
22
 * For more details and usage information on BaseListView, see the [guide article on data widgets](guide:output-data-widgets).
23
 *
24
 * @author Qiang Xue <[email protected]>
25
 * @since 2.0
26
 */
27
abstract class BaseListView extends Widget
28
{
29
    /**
30
     * @var array the HTML attributes for the container tag of the list view.
31
     * The "tag" element specifies the tag name of the container element and defaults to "div".
32
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
33
     */
34
    public $options = [];
35
    /**
36
     * @var \yii\data\DataProviderInterface the data provider for the view. This property is required.
37
     */
38
    public $dataProvider;
39
    /**
40
     * @var array the configuration for the pager widget. By default, [[LinkPager]] will be
41
     * used to render the pager. You can use a different widget class by configuring the "class" element.
42
     * Note that the widget must support the `pagination` property which will be populated with the
43
     * [[\yii\data\BaseDataProvider::pagination|pagination]] value of the [[dataProvider]].
44
     */
45
    public $pager = [];
46
    /**
47
     * @var array the configuration for the sorter widget. By default, [[LinkSorter]] will be
48
     * used to render the sorter. You can use a different widget class by configuring the "class" element.
49
     * Note that the widget must support the `sort` property which will be populated with the
50
     * [[\yii\data\BaseDataProvider::sort|sort]] value of the [[dataProvider]].
51
     */
52
    public $sorter = [];
53
    /**
54
     * @var string the HTML content to be displayed as the summary of the list view.
55
     * If you do not want to show the summary, you may set it with an empty string.
56
     *
57
     * The following tokens will be replaced with the corresponding values:
58
     *
59
     * - `{begin}`: the starting row number (1-based) currently being displayed
60
     * - `{end}`: the ending row number (1-based) currently being displayed
61
     * - `{count}`: the number of rows currently being displayed
62
     * - `{totalCount}`: the total number of rows available
63
     * - `{page}`: the page number (1-based) current being displayed
64
     * - `{pageCount}`: the number of pages available
65
     */
66
    public $summary;
67
    /**
68
     * @var array the HTML attributes for the summary of the list view.
69
     * The "tag" element specifies the tag name of the summary element and defaults to "div".
70
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
71
     */
72
    public $summaryOptions = ['class' => 'summary'];
73
    /**
74
     * @var bool whether to show an empty list view if [[dataProvider]] returns no data.
75
     * The default value is false which displays an element according to the [[emptyText]]
76
     * and [[emptyTextOptions]] properties.
77
     */
78
    public $showOnEmpty = false;
79
    /**
80
     * @var string|false the HTML content to be displayed when [[dataProvider]] does not have any data.
81
     * When this is set to `false` no extra HTML content will be generated.
82
     * The default value is the text "No results found." which will be translated to the current application language.
83
     * @see showOnEmpty
84
     * @see emptyTextOptions
85
     */
86
    public $emptyText;
87
    /**
88
     * @var array the HTML attributes for the emptyText of the list view.
89
     * The "tag" element specifies the tag name of the emptyText element and defaults to "div".
90
     * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
91
     */
92
    public $emptyTextOptions = ['class' => 'empty'];
93
    /**
94
     * @var string the layout that determines how different sections of the list view should be organized.
95
     * The following tokens will be replaced with the corresponding section contents:
96
     *
97
     * - `{summary}`: the summary section. See [[renderSummary()]].
98
     * - `{items}`: the list items. See [[renderItems()]].
99
     * - `{sorter}`: the sorter. See [[renderSorter()]].
100
     * - `{pager}`: the pager. See [[renderPager()]].
101
     */
102
    public $layout = "{summary}\n{items}\n{pager}";
103
104
105
    /**
106
     * Renders the data models.
107
     * @return string the rendering result.
108
     */
109
    abstract public function renderItems();
110
111
    /**
112
     * Initializes the view.
113
     */
114 26
    public function init()
115
    {
116 26
        if ($this->dataProvider === null) {
117
            throw new InvalidConfigException('The "dataProvider" property must be set.');
118
        }
119 26
        if ($this->emptyText === null) {
120 22
            $this->emptyText = Yii::t('yii', 'No results found.');
121
        }
122 26
        if (!isset($this->options['id'])) {
123 25
            $this->options['id'] = $this->getId();
124
        }
125 26
    }
126
127
    /**
128
     * Runs the widget.
129
     */
130 17
    public function run()
131
    {
132 17
        if ($this->showOnEmpty || $this->dataProvider->getCount() > 0) {
133 15
            $content = preg_replace_callback("/{\\w+}/", function ($matches) {
134 15
                $content = $this->renderSection($matches[0]);
135
136 15
                return $content === false ? $matches[0] : $content;
137 15
            }, $this->layout);
138
        } else {
139 2
            $content = $this->renderEmpty();
140
        }
141
142 17
        $options = $this->options;
143 17
        $tag = ArrayHelper::remove($options, 'tag', 'div');
144 17
        echo Html::tag($tag, $content, $options);
145 17
    }
146
147
    /**
148
     * Renders a section of the specified name.
149
     * If the named section is not supported, false will be returned.
150
     * @param string $name the section name, e.g., `{summary}`, `{items}`.
151
     * @return string|bool the rendering result of the section, or false if the named section is not supported.
152
     */
153 15
    public function renderSection($name)
154
    {
155
        switch ($name) {
156 15
            case '{summary}':
157 13
                return $this->renderSummary();
158 15
            case '{items}':
159 13
                return $this->renderItems();
160 15
            case '{pager}':
161 13
                return $this->renderPager();
162 2
            case '{sorter}':
163 2
                return $this->renderSorter();
164
            default:
165
                return false;
166
        }
167
    }
168
169
    /**
170
     * Renders the HTML content indicating that the list view has no data.
171
     * @return string the rendering result
172
     * @see emptyText
173
     */
174 4
    public function renderEmpty()
175
    {
176 4
        if ($this->emptyText === false) {
177 1
            return '';
178
        }
179 3
        $options = $this->emptyTextOptions;
180 3
        $tag = ArrayHelper::remove($options, 'tag', 'div');
181 3
        return Html::tag($tag, $this->emptyText, $options);
182
    }
183
184
    /**
185
     * Renders the summary text.
186
     */
187 13
    public function renderSummary()
188
    {
189 13
        $count = $this->dataProvider->getCount();
190 13
        if ($count <= 0) {
191 4
            return '';
192
        }
193 9
        $summaryOptions = $this->summaryOptions;
194 9
        $tag = ArrayHelper::remove($summaryOptions, 'tag', 'div');
195 9
        if (($pagination = $this->dataProvider->getPagination()) !== false) {
196 9
            $totalCount = $this->dataProvider->getTotalCount();
197 9
            $begin = $pagination->getPage() * $pagination->pageSize + 1;
198 9
            $end = $begin + $count - 1;
199 9
            if ($begin > $end) {
200
                $begin = $end;
201
            }
202 9
            $page = $pagination->getPage() + 1;
203 9
            $pageCount = $pagination->pageCount;
204 9
            if (($summaryContent = $this->summary) === null) {
205 9
                return Html::tag($tag, Yii::t('yii', 'Showing <b>{begin, number}-{end, number}</b> of <b>{totalCount, number}</b> {totalCount, plural, one{item} other{items}}.', [
206 9
                        'begin' => $begin,
207 9
                        'end' => $end,
208 9
                        'count' => $count,
209 9
                        'totalCount' => $totalCount,
210 9
                        'page' => $page,
211 9
                        'pageCount' => $pageCount,
212 9
                    ]), $summaryOptions);
213
            }
214
        } else {
215
            $begin = $page = $pageCount = 1;
216
            $end = $totalCount = $count;
217
            if (($summaryContent = $this->summary) === null) {
218
                return Html::tag($tag, Yii::t('yii', 'Total <b>{count, number}</b> {count, plural, one{item} other{items}}.', [
219
                    'begin' => $begin,
220
                    'end' => $end,
221
                    'count' => $count,
222
                    'totalCount' => $totalCount,
223
                    'page' => $page,
224
                    'pageCount' => $pageCount,
225
                ]), $summaryOptions);
226
            }
227
        }
228
229
        return Yii::$app->getI18n()->format($summaryContent, [
230
            'begin' => $begin,
231
            'end' => $end,
232
            'count' => $count,
233
            'totalCount' => $totalCount,
234
            'page' => $page,
235
            'pageCount' => $pageCount,
236
        ], Yii::$app->language);
237
    }
238
239
    /**
240
     * Renders the pager.
241
     * @return string the rendering result
242
     */
243 13
    public function renderPager()
244
    {
245 13
        $pagination = $this->dataProvider->getPagination();
246 13
        if ($pagination === false || $this->dataProvider->getCount() <= 0) {
247 4
            return '';
248
        }
249
        /* @var $class LinkPager */
250 9
        $pager = $this->pager;
251 9
        $class = ArrayHelper::remove($pager, 'class', LinkPager::className());
252 9
        $pager['pagination'] = $pagination;
253 9
        $pager['view'] = $this->getView();
254
255 9
        return $class::widget($pager);
256
    }
257
258
    /**
259
     * Renders the sorter.
260
     * @return string the rendering result
261
     */
262 2
    public function renderSorter()
263
    {
264 2
        $sort = $this->dataProvider->getSort();
265 2
        if ($sort === false || empty($sort->attributes) || $this->dataProvider->getCount() <= 0) {
266
            return '';
267
        }
268
        /* @var $class LinkSorter */
269 2
        $sorter = $this->sorter;
270 2
        $class = ArrayHelper::remove($sorter, 'class', LinkSorter::className());
271 2
        $sorter['sort'] = $sort;
272 2
        $sorter['view'] = $this->getView();
273
274 2
        return $class::widget($sorter);
275
    }
276
}
277