Passed
Push — scrutinizer-migrate-to-new-eng... ( 58afd6 )
by Alexander
18:11
created

SqlDataProvider::prepareModels()   A

Complexity

Conditions 6
Paths 7

Size

Total Lines 30
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.1215

Importance

Changes 0
Metric Value
cc 6
eloc 19
nc 7
nop 0
dl 0
loc 30
ccs 17
cts 20
cp 0.85
crap 6.1215
rs 9.0111
c 0
b 0
f 0
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\InvalidConfigException;
12
use yii\db\Connection;
13
use yii\db\Expression;
14
use yii\db\Query;
15
use yii\di\Instance;
16
17
/**
18
 * SqlDataProvider implements a data provider based on a plain SQL statement.
19
 *
20
 * SqlDataProvider provides data in terms of arrays, each representing a row of query result.
21
 *
22
 * Like other data providers, SqlDataProvider also supports sorting and pagination.
23
 * It does so by modifying the given [[sql]] statement with "ORDER BY" and "LIMIT"
24
 * clauses. You may configure the [[sort]] and [[pagination]] properties to
25
 * customize sorting and pagination behaviors.
26
 *
27
 * SqlDataProvider may be used in the following way:
28
 *
29
 * ```php
30
 * $count = Yii::$app->db->createCommand('
31
 *     SELECT COUNT(*) FROM user WHERE status=:status
32
 * ', [':status' => 1])->queryScalar();
33
 *
34
 * $dataProvider = new SqlDataProvider([
35
 *     'sql' => 'SELECT * FROM user WHERE status=:status',
36
 *     'params' => [':status' => 1],
37
 *     'totalCount' => $count,
38
 *     'sort' => [
39
 *         'attributes' => [
40
 *             'age',
41
 *             'name' => [
42
 *                 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
43
 *                 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
44
 *                 'default' => SORT_DESC,
45
 *                 'label' => 'Name',
46
 *             ],
47
 *         ],
48
 *     ],
49
 *     'pagination' => [
50
 *         'pageSize' => 20,
51
 *     ],
52
 * ]);
53
 *
54
 * // get the user records in the current page
55
 * $models = $dataProvider->getModels();
56
 * ```
57
 *
58
 * Note: if you want to use the pagination feature, you must configure the [[totalCount]] property
59
 * to be the total number of rows (without pagination). And if you want to use the sorting feature,
60
 * you must configure the [[sort]] property so that the provider knows which columns can be sorted.
61
 *
62
 * For more details and usage information on SqlDataProvider, see the [guide article on data providers](guide:output-data-providers).
63
 *
64
 * @author Qiang Xue <[email protected]>
65
 * @since 2.0
66
 */
67
class SqlDataProvider extends BaseDataProvider
68
{
69
    /**
70
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
71
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
72
     */
73
    public $db = 'db';
74
    /**
75
     * @var string the SQL statement to be used for fetching data rows.
76
     */
77
    public $sql;
78
    /**
79
     * @var array parameters (name=>value) to be bound to the SQL statement.
80
     */
81
    public $params = [];
82
    /**
83
     * @var string|callable the column that is used as the key of the data models.
84
     * This can be either a column name, or a callable that returns the key value of a given data model.
85
     *
86
     * If this is not set, the keys of the [[models]] array will be used.
87
     */
88
    public $key;
89
90
91
    /**
92
     * Initializes the DB connection component.
93
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
94
     * @throws InvalidConfigException if [[db]] is invalid.
95
     */
96 3
    public function init()
97
    {
98 3
        parent::init();
99 3
        $this->db = Instance::ensure($this->db, Connection::className());
0 ignored issues
show
Deprecated Code introduced by
The function yii\base\BaseObject::className() has been deprecated: since 2.0.14. On PHP >=5.5, use `::class` instead. ( Ignorable by Annotation )

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

99
        $this->db = Instance::ensure($this->db, /** @scrutinizer ignore-deprecated */ Connection::className());

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

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

Loading history...
100 3
        if ($this->sql === null) {
101
            throw new InvalidConfigException('The "sql" property must be set.');
102
        }
103 3
    }
104
105
    /**
106
     * {@inheritdoc}
107
     */
108 1
    protected function prepareModels()
109
    {
110 1
        $sort = $this->getSort();
111 1
        $pagination = $this->getPagination();
112 1
        if ($pagination === false && $sort === false) {
0 ignored issues
show
introduced by
The condition $pagination === false is always false.
Loading history...
113
            return $this->db->createCommand($this->sql, $this->params)->queryAll();
114
        }
115
116 1
        $sql = $this->sql;
117 1
        $orders = [];
118 1
        $limit = $offset = null;
119
120 1
        if ($sort !== false) {
121 1
            $orders = $sort->getOrders();
122 1
            $pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
123 1
            if (preg_match($pattern, $sql, $matches)) {
124
                array_unshift($orders, new Expression($matches[1]));
125
                $sql = preg_replace($pattern, '', $sql);
126
            }
127
        }
128
129 1
        if ($pagination !== false) {
0 ignored issues
show
introduced by
The condition $pagination !== false is always true.
Loading history...
130 1
            $pagination->totalCount = $this->getTotalCount();
131 1
            $limit = $pagination->getLimit();
132 1
            $offset = $pagination->getOffset();
133
        }
134
135 1
        $sql = $this->db->getQueryBuilder()->buildOrderByAndLimit($sql, $orders, $limit, $offset);
136
137 1
        return $this->db->createCommand($sql, $this->params)->queryAll();
138
    }
139
140
    /**
141
     * {@inheritdoc}
142
     */
143 1
    protected function prepareKeys($models)
144
    {
145 1
        $keys = [];
146 1
        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 1
        return array_keys($models);
159
    }
160
161
    /**
162
     * {@inheritdoc}
163
     */
164 3
    protected function prepareTotalCount()
165
    {
166 3
        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 3
            'from' => ['sub' => "({$this->sql})"],
168 3
            'params' => $this->params,
169 3
        ]))->count('*', $this->db);
170
    }
171
}
172