Passed
Pull Request — master (#20070)
by Loban
11:52 queued 03:24
created

ArrayDataProvider   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 86
Duplicated Lines 0 %

Test Coverage

Coverage 72%

Importance

Changes 0
Metric Value
eloc 26
c 0
b 0
f 0
dl 0
loc 86
ccs 18
cts 25
cp 0.72
rs 10
wmc 13

4 Methods

Rating   Name   Duplication   Size   Complexity  
A prepareKeys() 0 16 4
A prepareModels() 0 15 5
A sortModels() 0 8 2
A prepareTotalCount() 0 3 2
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://www.yiiframework.com/license/
6
 */
7
8
namespace yii\data;
9
10
use yii\helpers\ArrayHelper;
11
12
/**
13
 * ArrayDataProvider implements a data provider based on a data array.
14
 *
15
 * The [[allModels]] property contains all data models that may be sorted and/or paginated.
16
 * ArrayDataProvider will provide the data after sorting and/or pagination.
17
 * You may configure the [[sort]] and [[pagination]] properties to
18
 * customize the sorting and pagination behaviors.
19
 *
20
 * Elements in the [[allModels]] array may be either objects (e.g. model objects)
21
 * or associative arrays (e.g. query results of DAO).
22
 * Make sure to set the [[key]] property to the name of the field that uniquely
23
 * identifies a data record or false if you do not have such a field.
24
 *
25
 * Compared to [[ActiveDataProvider]], ArrayDataProvider could be less efficient
26
 * because it needs to have [[allModels]] ready.
27
 *
28
 * ArrayDataProvider may be used in the following way:
29
 *
30
 * ```php
31
 * $query = new Query;
32
 * $provider = new ArrayDataProvider([
33
 *     'allModels' => $query->from('post')->all(),
34
 *     'sort' => [
35
 *         'attributes' => ['id', 'username', 'email'],
36
 *     ],
37
 *     'pagination' => [
38
 *         'pageSize' => 10,
39
 *     ],
40
 * ]);
41
 * // get the posts in the current page
42
 * $posts = $provider->getModels();
43
 * ```
44
 *
45
 * Note: if you want to use the sorting feature, you must configure the [[sort]] property
46
 * so that the provider knows which columns can be sorted.
47
 *
48
 * For more details and usage information on ArrayDataProvider, see the [guide article on data providers](guide:output-data-providers).
49
 *
50
 * @author Qiang Xue <[email protected]>
51
 * @since 2.0
52
 */
53
class ArrayDataProvider extends BaseDataProvider
54
{
55
    /**
56
     * @var string|callable|null the column that is used as the key of the data models.
57
     * This can be either a column name, or a callable that returns the key value of a given data model.
58
     * If this is not set, the index of the [[models]] array will be used.
59
     * @see getKeys()
60
     */
61
    public $key;
62
    /**
63
     * @var array the data that is not paginated or sorted. When pagination is enabled,
64
     * this property usually contains more elements than [[models]].
65
     * The array elements must use zero-based integer keys.
66
     */
67
    public $allModels;
68
    /**
69
     * @var string the name of the [[\yii\base\Model|Model]] class that will be represented.
70
     * This property is used to get columns' names.
71
     * @since 2.0.9
72
     */
73
    public $modelClass;
74
75
76
    /**
77
     * {@inheritdoc}
78
     */
79 45
    protected function prepareModels()
80
    {
81 45
        if (($models = $this->allModels) === null) {
0 ignored issues
show
introduced by
The condition $models = $this->allModels === null is always false.
Loading history...
82
            return [];
83
        }
84
85 45
        if (($sort = $this->getSort()) !== false) {
86 44
            $models = $this->sortModels($models, $sort);
0 ignored issues
show
Bug introduced by
It seems like $sort can also be of type true; however, parameter $sort of yii\data\ArrayDataProvider::sortModels() does only seem to accept yii\data\Sort, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

86
            $models = $this->sortModels($models, /** @scrutinizer ignore-type */ $sort);
Loading history...
87
        }
88
89 45
        $pagination = $this->getPagination();
90 45
        if ($pagination !== false && $pagination->getPageSize() > 0) {
91 44
            $models = array_slice($models, $pagination->getOffset(), $pagination->getLimit(), true);
92
        }
93 45
        return $models;
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 45
    protected function prepareKeys($models)
100
    {
101 45
        if ($this->key !== null) {
102
            $keys = [];
103
            foreach ($models as $model) {
104
                if (is_string($this->key)) {
105
                    $keys[] = $model[$this->key];
106
                } else {
107
                    $keys[] = call_user_func($this->key, $model);
108
                }
109
            }
110
111
            return $keys;
112
        }
113
114 45
        return array_keys($models);
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 29
    protected function prepareTotalCount()
121
    {
122 29
        return is_array($this->allModels) ? count($this->allModels) : 0;
0 ignored issues
show
introduced by
The condition is_array($this->allModels) is always true.
Loading history...
123
    }
124
125
    /**
126
     * Sorts the data models according to the given sort definition.
127
     * @param array $models the models to be sorted
128
     * @param Sort $sort the sort definition
129
     * @return array the sorted data models
130
     */
131 44
    protected function sortModels($models, $sort)
132
    {
133 44
        $orders = $sort->getOrders();
134 44
        if (!empty($orders)) {
135 4
            ArrayHelper::multisort($models, array_keys($orders), array_values($orders), $sort->sortFlags);
136
        }
137
138 44
        return $models;
139
    }
140
}
141