Passed
Pull Request — 2.2 (#20357)
by Wilmer
10:52 queued 03:12
created

SqlDataProvider::prepareModels()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 6.0052

Importance

Changes 0
Metric Value
cc 6
eloc 18
nc 7
nop 0
dl 0
loc 29
ccs 18
cts 19
cp 0.9474
crap 6.0052
rs 9.0444
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\data;
10
11
use Yii;
12
use yii\base\InvalidConfigException;
13
use yii\db\Connection;
14
use yii\db\Expression;
15
use yii\db\Query;
16
use yii\di\Instance;
17
18
/**
19
 * SqlDataProvider implements a data provider based on a plain SQL statement.
20
 *
21
 * SqlDataProvider provides data in terms of arrays, each representing a row of query result.
22
 *
23
 * Like other data providers, SqlDataProvider also supports sorting and pagination.
24
 * It does so by modifying the given [[sql]] statement with "ORDER BY" and "LIMIT"
25
 * clauses. You may configure the [[sort]] and [[pagination]] properties to
26
 * customize sorting and pagination behaviors.
27
 *
28
 * SqlDataProvider may be used in the following way:
29
 *
30
 * ```php
31
 * $count = Yii::$app->db->createCommand('
32
 *     SELECT COUNT(*) FROM user WHERE status=:status
33
 * ', [':status' => 1])->queryScalar();
34
 *
35
 * $dataProvider = new SqlDataProvider([
36
 *     'sql' => 'SELECT * FROM user WHERE status=:status',
37
 *     'params' => [':status' => 1],
38
 *     'totalCount' => $count,
39
 *     'sort' => [
40
 *         'attributes' => [
41
 *             'age',
42
 *             'name' => [
43
 *                 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
44
 *                 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
45
 *                 'default' => SORT_DESC,
46
 *                 'label' => 'Name',
47
 *             ],
48
 *         ],
49
 *     ],
50
 *     'pagination' => [
51
 *         'pageSize' => 20,
52
 *     ],
53
 * ]);
54
 *
55
 * // get the user records in the current page
56
 * $models = $dataProvider->getModels();
57
 * ```
58
 *
59
 * Note: if you want to use the pagination feature, you must configure the [[totalCount]] property
60
 * to be the total number of rows (without pagination). And if you want to use the sorting feature,
61
 * you must configure the [[sort]] property so that the provider knows which columns can be sorted.
62
 *
63
 * For more details and usage information on SqlDataProvider, see the [guide article on data providers](guide:output-data-providers).
64
 *
65
 * @author Qiang Xue <[email protected]>
66
 * @since 2.0
67
 */
68
class SqlDataProvider extends BaseDataProvider
69
{
70
    /**
71
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
72
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
73
     */
74
    public $db = 'db';
75
    /**
76
     * @var string the SQL statement to be used for fetching data rows.
77
     */
78
    public $sql;
79
    /**
80
     * @var array parameters (name=>value) to be bound to the SQL statement.
81
     */
82
    public $params = [];
83
    /**
84
     * @var string|callable|null the column that is used as the key of the data models.
85
     * This can be either a column name, or a callable that returns the key value of a given data model.
86
     *
87
     * If this is not set, the keys of the [[models]] array will be used.
88
     */
89
    public $key;
90
91
92
    /**
93
     * Initializes the DB connection component.
94
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
95
     * @throws InvalidConfigException if [[db]] is invalid.
96
     */
97 11
    public function init()
98
    {
99 11
        parent::init();
100 11
        $this->db = Instance::ensure($this->db, Connection::class);
101 11
        if ($this->sql === null) {
102
            throw new InvalidConfigException('The "sql" property must be set.');
103
        }
104
    }
105
106
    /**
107
     * {@inheritdoc}
108
     */
109 9
    protected function prepareModels()
110
    {
111 9
        $sort = $this->getSort();
112 9
        $pagination = $this->getPagination();
113 9
        if ($pagination === false && $sort === false) {
114
            return $this->db->createCommand($this->sql, $this->params)->queryAll();
115
        }
116
117 9
        $sql = $this->sql;
118 9
        $orders = [];
119 9
        $limit = $offset = null;
120
121 9
        if ($sort !== false) {
122 9
            $orders = $sort->getOrders();
123 9
            $pattern = '/\s+order\s+by\s+([\w\s,\."`\[\]]+)$/i';
124 9
            if (preg_match($pattern, $sql, $matches)) {
125 8
                array_unshift($orders, new Expression($matches[1]));
126 8
                $sql = preg_replace($pattern, '', $sql);
127
            }
128
        }
129
130 9
        if ($pagination !== false) {
131 9
            $limit = $pagination->getLimit();
132 9
            $offset = $pagination->getOffset();
133
        }
134
135 9
        $sql = $this->db->getQueryBuilder()->buildOrderByAndLimit($sql, $orders, $limit, $offset);
136
137 9
        return $this->db->createCommand($sql, $this->params)->queryAll();
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 9
    protected function prepareKeys($models)
144
    {
145 9
        $keys = [];
146 9
        if ($this->key !== null) {
147
            foreach ($models as $model) {
148
                if (is_string($this->key)) {
149
                    $keys[] = $model[$this->key];
150
                } else {
151
                    $keys[] = call_user_func($this->key, $model);
152
                }
153
            }
154
155
            return $keys;
156
        }
157
158 9
        return array_keys($models);
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164 11
    protected function prepareTotalCount()
165
    {
166 11
        return (new Query([
0 ignored issues
show
Bug Best Practice introduced by
The expression return new yii\db\Query(...->count('*', $this->db) also could return the type string which is incompatible with the return type mandated by yii\data\BaseDataProvider::prepareTotalCount() of integer.
Loading history...
167 11
            'from' => ['sub' => "({$this->sql})"],
168 11
            'params' => $this->params,
169 11
        ]))->count('*', $this->db);
170
    }
171
}
172