Passed
Pull Request — master (#20176)
by Loban
08:04
created

ActiveDataProvider::setSort()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 11
nc 5
nop 1
dl 0
loc 17
ccs 13
cts 13
cp 1
crap 6
rs 9.2222
c 0
b 0
f 0
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\base\InvalidConfigException;
11
use yii\base\Model;
12
use yii\caching\ArrayCache;
13
use yii\db\ActiveQueryInterface;
14
use yii\db\Connection;
15
use yii\db\QueryInterface;
16
use yii\di\Instance;
17
18
/**
19
 * ActiveDataProvider implements a data provider based on [[\yii\db\Query]] and [[\yii\db\ActiveQuery]].
20
 *
21
 * ActiveDataProvider provides data by performing DB queries using [[query]].
22
 *
23
 * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
24
 *
25
 * ```php
26
 * $provider = new ActiveDataProvider([
27
 *     'query' => Post::find(),
28
 *     'pagination' => [
29
 *         'pageSize' => 20,
30
 *     ],
31
 * ]);
32
 *
33
 * // get the posts in the current page
34
 * $posts = $provider->getModels();
35
 * ```
36
 *
37
 * And the following example shows how to use ActiveDataProvider without ActiveRecord:
38
 *
39
 * ```php
40
 * $query = new Query();
41
 * $provider = new ActiveDataProvider([
42
 *     'query' => $query->from('post'),
43
 *     'pagination' => [
44
 *         'pageSize' => 20,
45
 *     ],
46
 * ]);
47
 *
48
 * // get the posts in the current page
49
 * $posts = $provider->getModels();
50
 * ```
51
 *
52
 * For more details and usage information on ActiveDataProvider, see the [guide article on data providers](guide:output-data-providers).
53
 *
54
 * @author Qiang Xue <[email protected]>
55
 * @since 2.0
56
 */
57
class ActiveDataProvider extends BaseDataProvider
58
{
59
    /**
60
     * @var QueryInterface|null the query that is used to fetch data models and [[totalCount]] if it is not explicitly set.
61
     */
62
    public $query;
63
    /**
64
     * @var string|callable|null the column that is used as the key of the data models.
65
     * This can be either a column name, or a callable that returns the key value of a given data model.
66
     *
67
     * If this is not set, the following rules will be used to determine the keys of the data models:
68
     *
69
     * - If [[query]] is an [[\yii\db\ActiveQuery]] instance, the primary keys of [[\yii\db\ActiveQuery::modelClass]] will be used.
70
     * - Otherwise, the keys of the [[models]] array will be used.
71
     *
72
     * @see getKeys()
73
     */
74
    public $key;
75
    /**
76
     * @var Connection|array|string|null the DB connection object or the application component ID of the DB connection.
77
     * If set it overrides [[query]] default DB connection.
78
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
79
     */
80
    public $db;
81
82
83
    /**
84
     * Initializes the DB connection component.
85
     * This method will initialize the [[db]] property (when set) to make sure it refers to a valid DB connection.
86
     * @throws InvalidConfigException if [[db]] is invalid.
87
     */
88 35
    public function init()
89
    {
90 35
        parent::init();
91 35
        if ($this->db !== null) {
92 12
            $this->db = Instance::ensure($this->db);
93
        }
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99 25
    protected function prepareModels()
100
    {
101 25
        if (!$this->query instanceof QueryInterface) {
102
            throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
103
        }
104 25
        $query = clone $this->query;
105 25
        if (($pagination = $this->getPagination()) !== false) {
106 25
            if ($pagination->totalCount === 0) {
107 4
                return [];
108
            }
109 21
            $query->limit($pagination->getLimit())->offset($pagination->getOffset());
110
        }
111 21
        if (($sort = $this->getSort()) !== false) {
112 21
            $query->addOrderBy($sort->getOrders());
113
        }
114 21
        return $query->all($this->db);
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 27
    protected function prepareKeys($models)
121
    {
122 27
        $keys = [];
123 27
        if ($this->key !== null) {
124
            foreach ($models as $model) {
125
                if (is_string($this->key)) {
126
                    $keys[] = $model[$this->key];
127
                } else {
128
                    $keys[] = call_user_func($this->key, $model);
129
                }
130
            }
131
            return $keys;
132 27
        } elseif ($this->query instanceof ActiveQueryInterface) {
133
            /* @var $class \yii\db\ActiveRecordInterface */
134 15
            $class = $this->query->modelClass;
0 ignored issues
show
Bug introduced by
Accessing modelClass on the interface yii\db\ActiveQueryInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
135 15
            $pks = $class::primaryKey();
136 15
            if (count($pks) === 1) {
137 15
                $pk = $pks[0];
138 15
                foreach ($models as $model) {
139 14
                    $keys[] = $model[$pk];
140
                }
141
            } else {
142
                foreach ($models as $model) {
143
                    $kk = [];
144
                    foreach ($pks as $pk) {
145
                        $kk[$pk] = $model[$pk];
146
                    }
147
                    $keys[] = $kk;
148
                }
149
            }
150 15
            return $keys;
151
        }
152 12
        return array_keys($models);
153
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158 25
    protected function prepareTotalCount()
159
    {
160 25
        if (!$this->query instanceof QueryInterface) {
161
            throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
162
        }
163 25
        $query = (clone $this->query)->limit(-1)->offset(-1)->orderBy([]);
164
165 25
        return $this->getQueryCache()->getOrSet((string)$query, function () use ($query) {
166 25
            return (int) $query->count('*', $this->db);
167 25
        });
168
    }
169
170
    private $_queryCache;
171
172
    /**
173
     * @return \yii\caching\CacheInterface
174
     */
175 25
    protected function getQueryCache()
176
    {
177 25
        if ($this->_queryCache === null) {
178 25
            $this->_queryCache = new ArrayCache();
179
        }
180 25
        return $this->_queryCache;
181
    }
182
183
    /**
184
     * {@inheritdoc}
185
     */
186 30
    public function setSort($value)
187
    {
188 30
        parent::setSort($value);
189 30
        if ($this->query instanceof ActiveQueryInterface && ($sort = $this->getSort()) !== false) {
190
            /* @var $modelClass Model */
191 20
            $modelClass = $this->query->modelClass;
192 20
            $model = $modelClass::instance();
193 20
            if (empty($sort->attributes)) {
194 16
                foreach ($model->attributes() as $attribute) {
195 16
                    $sort->attributes[$attribute] = [
196 16
                        'asc' => [$attribute => SORT_ASC],
197 16
                        'desc' => [$attribute => SORT_DESC],
198 16
                    ];
199
                }
200
            }
201 20
            if ($sort->modelClass === null) {
202 20
                $sort->modelClass = $modelClass;
0 ignored issues
show
Documentation Bug introduced by
It seems like $modelClass of type yii\base\Model is incompatible with the declared type null|string of property $modelClass.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
203
            }
204
        }
205
    }
206
207 1
    public function __clone()
208
    {
209 1
        if (is_object($this->query)) {
210 1
            $this->query = clone $this->query;
211
        }
212 1
        parent::__clone();
213
    }
214
}
215