Completed
Pull Request — master (#16756)
by Vladimir
13:05
created

BaseDataProvider   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 246
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 78.56%

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 5
dl 0
loc 246
ccs 55
cts 70
cp 0.7856
rs 9.84
c 0
b 0
f 0

17 Methods

Rating   Name   Duplication   Size   Complexity  
prepareModels() 0 1 ?
prepareKeys() 0 1 ?
prepareTotalCount() 0 1 ?
A init() 0 10 3
A prepare() 0 9 5
A getModels() 0 6 1
A setModels() 0 4 1
A getKeys() 0 6 1
A setKeys() 0 4 1
A getCount() 0 4 1
A getTotalCount() 0 10 3
A setTotalCount() 0 4 1
A getPagination() 0 8 2
A setPagination() 0 15 5
A getSort() 0 8 2
A setSort() 0 14 5
A refresh() 0 6 1
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\data;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidArgumentException;
13
14
/**
15
 * BaseDataProvider provides a base class that implements the [[DataProviderInterface]].
16
 *
17
 * For more details and usage information on BaseDataProvider, see the [guide article on data providers](guide:output-data-providers).
18
 *
19
 * @property int $count The number of data models in the current page. This property is read-only.
20
 * @property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is
21
 * uniquely identified by the corresponding key value in this array.
22
 * @property array $models The list of data models in the current page.
23
 * @property Pagination|false $pagination The pagination object. If this is false, it means the pagination is
24
 * disabled. Note that the type of this property differs in getter and setter. See [[getPagination()]] and
25
 * [[setPagination()]] for details.
26
 * @property Sort|bool $sort The sorting object. If this is false, it means the sorting is disabled. Note that
27
 * the type of this property differs in getter and setter. See [[getSort()]] and [[setSort()]] for details.
28
 * @property int $totalCount Total number of possible data models.
29
 *
30
 * @author Qiang Xue <[email protected]>
31
 * @since 2.0
32
 */
33
abstract class BaseDataProvider extends Component implements DataProviderInterface
34
{
35
    /**
36
     * @var int Number of data providers on the current page. Used to generate unique IDs.
37
     */
38
    private static $counter = 0;
39
    /**
40
     * @var string an ID that uniquely identifies the data provider among all data providers.
41
     * Generated automatically the following way in case it is not set:
42
     *
43
     * - First data provider ID is empty.
44
     * - Second and all subsequent data provider IDs are: "dp-1", "dp-2", etc.
45
     */
46
    public $id;
47
48
    private $_sort;
49
    private $_pagination;
50
    private $_keys;
51
    private $_models;
52
    private $_totalCount;
53
54
55
    /**
56
     * {@inheritdoc}
57
     */
58 61
    public function init()
59
    {
60 61
        parent::init();
61 61
        if ($this->id === null) {
62 61
            if (self::$counter > 0) {
63 61
                $this->id = 'dp-' . self::$counter;
64
            }
65 61
            self::$counter++;
66
        }
67 61
    }
68
69
    /**
70
     * Prepares the data models that will be made available in the current page.
71
     * @return array the available data models
72
     */
73
    abstract protected function prepareModels();
74
75
    /**
76
     * Prepares the keys associated with the currently available data models.
77
     * @param array $models the available data models
78
     * @return array the keys
79
     */
80
    abstract protected function prepareKeys($models);
81
82
    /**
83
     * Returns a value indicating the total number of data models in this data provider.
84
     * @return int total number of data models in this data provider.
85
     */
86
    abstract protected function prepareTotalCount();
87
88
    /**
89
     * Prepares the data models and keys.
90
     *
91
     * This method will prepare the data models and keys that can be retrieved via
92
     * [[getModels()]] and [[getKeys()]].
93
     *
94
     * This method will be implicitly called by [[getModels()]] and [[getKeys()]] if it has not been called before.
95
     *
96
     * @param bool $forcePrepare whether to force data preparation even if it has been done before.
97
     */
98 50
    public function prepare($forcePrepare = false)
99
    {
100 50
        if ($forcePrepare || $this->_models === null) {
101 48
            $this->_models = $this->prepareModels();
102
        }
103 50
        if ($forcePrepare || $this->_keys === null) {
104 50
            $this->_keys = $this->prepareKeys($this->_models);
105
        }
106 50
    }
107
108
    /**
109
     * Returns the data models in the current page.
110
     * @return array the list of data models in the current page.
111
     */
112 50
    public function getModels()
113
    {
114 50
        $this->prepare();
115
116 50
        return $this->_models;
117
    }
118
119
    /**
120
     * Sets the data models in the current page.
121
     * @param array $models the models in the current page
122
     */
123 2
    public function setModels($models)
124
    {
125 2
        $this->_models = $models;
126 2
    }
127
128
    /**
129
     * Returns the key values associated with the data models.
130
     * @return array the list of key values corresponding to [[models]]. Each data model in [[models]]
131
     * is uniquely identified by the corresponding key value in this array.
132
     */
133 26
    public function getKeys()
134
    {
135 26
        $this->prepare();
136
137 26
        return $this->_keys;
138
    }
139
140
    /**
141
     * Sets the key values associated with the data models.
142
     * @param array $keys the list of key values corresponding to [[models]].
143
     */
144
    public function setKeys($keys)
145
    {
146
        $this->_keys = $keys;
147
    }
148
149
    /**
150
     * Returns the number of data models in the current page.
151
     * @return int the number of data models in the current page.
152
     */
153 18
    public function getCount()
154
    {
155 18
        return count($this->getModels());
156
    }
157
158
    /**
159
     * Returns the total number of data models.
160
     * When [[pagination]] is false, this returns the same value as [[count]].
161
     * Otherwise, it will call [[prepareTotalCount()]] to get the count.
162
     * @return int total number of possible data models.
163
     */
164 50
    public function getTotalCount()
165
    {
166 50
        if ($this->getPagination() === false) {
167
            return $this->getCount();
168 50
        } elseif ($this->_totalCount === null) {
169 47
            $this->_totalCount = $this->prepareTotalCount();
170
        }
171
172 50
        return $this->_totalCount;
173
    }
174
175
    /**
176
     * Sets the total number of data models.
177
     * @param int $value the total number of data models.
178
     */
179 10
    public function setTotalCount($value)
180
    {
181 10
        $this->_totalCount = $value;
182 10
    }
183
184
    /**
185
     * Returns the pagination object used by this data provider.
186
     * Note that you should call [[prepare()]] or [[getModels()]] first to get correct values
187
     * of [[Pagination::totalCount]] and [[Pagination::pageCount]].
188
     * @return Pagination|false the pagination object. If this is false, it means the pagination is disabled.
189
     */
190 50
    public function getPagination()
191
    {
192 50
        if ($this->_pagination === null) {
193 50
            $this->setPagination([]);
194
        }
195
196 50
        return $this->_pagination;
197
    }
198
199
    /**
200
     * Sets the pagination for this data provider.
201
     * @param array|Pagination|bool $value the pagination to be used by this data provider.
202
     * This can be one of the following:
203
     *
204
     * - a configuration array for creating the pagination object. The "class" element defaults
205
     *   to 'yii\data\Pagination'
206
     * - an instance of [[Pagination]] or its subclass
207
     * - false, if pagination needs to be disabled.
208
     *
209
     * @throws InvalidArgumentException
210
     */
211 52
    public function setPagination($value)
212
    {
213 52
        if (is_array($value)) {
214 52
            $config = ['class' => Pagination::className()];
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
215 52
            if ($this->id !== null) {
216 50
                $config['pageParam'] = $this->id . '-page';
217 50
                $config['pageSizeParam'] = $this->id . '-per-page';
218
            }
219 52
            $this->_pagination = Yii::createObject(array_merge($config, $value));
220
        } elseif ($value instanceof Pagination || $value === false) {
221
            $this->_pagination = $value;
222
        } else {
223
            throw new InvalidArgumentException('Only Pagination instance, configuration array or false is allowed.');
224
        }
225 50
    }
226
227
    /**
228
     * Returns the sorting object used by this data provider.
229
     * @return Sort|bool the sorting object. If this is false, it means the sorting is disabled.
230
     */
231 47
    public function getSort()
232
    {
233 47
        if ($this->_sort === null) {
234 43
            $this->setSort([]);
235
        }
236
237 47
        return $this->_sort;
238
    }
239
240
    /**
241
     * Sets the sort definition for this data provider.
242
     * @param array|Sort|bool $value the sort definition to be used by this data provider.
243
     * This can be one of the following:
244
     *
245
     * - a configuration array for creating the sort definition object. The "class" element defaults
246
     *   to 'yii\data\Sort'
247
     * - an instance of [[Sort]] or its subclass
248
     * - false, if sorting needs to be disabled.
249
     *
250
     * @throws InvalidArgumentException
251
     */
252 48
    public function setSort($value)
253
    {
254 48
        if (is_array($value)) {
255 48
            $config = ['class' => Sort::className()];
0 ignored issues
show
Deprecated Code introduced by
The method yii\base\BaseObject::className() has been deprecated with message: since 2.0.14. On PHP >=5.5, use `::class` instead.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
256 48
            if ($this->id !== null) {
257 43
                $config['sortParam'] = $this->id . '-sort';
258
            }
259 48
            $this->_sort = Yii::createObject(array_merge($config, $value));
260
        } elseif ($value instanceof Sort || $value === false) {
261
            $this->_sort = $value;
262
        } else {
263
            throw new InvalidArgumentException('Only Sort instance, configuration array or false is allowed.');
264
        }
265 48
    }
266
267
    /**
268
     * Refreshes the data provider.
269
     * After calling this method, if [[getModels()]], [[getKeys()]] or [[getTotalCount()]] is called again,
270
     * they will re-execute the query and return the latest data available.
271
     */
272
    public function refresh()
273
    {
274
        $this->_totalCount = null;
275
        $this->_models = null;
276
        $this->_keys = null;
277
    }
278
}
279