|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165 |
- <?php
-
-
- namespace yii\data;
-
- use Yii;
- use yii\base\InvalidConfigException;
- use yii\db\Connection;
- use yii\db\Expression;
- use yii\di\Instance;
-
-
- class SqlDataProvider extends BaseDataProvider
- {
-
-
- public $db = 'db';
-
-
- public $sql;
-
-
- public $params = [];
-
-
- public $key;
-
-
-
-
- public function init()
- {
- parent::init();
- $this->db = Instance::ensure($this->db, Connection::className());
- if ($this->sql === null) {
- throw new InvalidConfigException('The "sql" property must be set.');
- }
- }
-
-
-
- protected function prepareModels()
- {
- $sort = $this->getSort();
- $pagination = $this->getPagination();
- if ($pagination === false && $sort === false) {
- return $this->db->createCommand($this->sql, $this->params)->queryAll();
- }
-
- $sql = $this->sql;
- $orders = [];
- $limit = $offset = null;
-
- if ($sort !== false) {
- $orders = $sort->getOrders();
- $pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
- if (preg_match($pattern, $sql, $matches)) {
- array_unshift($orders, new Expression($matches[1]));
- $sql = preg_replace($pattern, '', $sql);
- }
- }
-
- if ($pagination !== false) {
- $pagination->totalCount = $this->getTotalCount();
- $limit = $pagination->getLimit();
- $offset = $pagination->getOffset();
- }
-
- $sql = $this->db->getQueryBuilder()->buildOrderByAndLimit($sql, $orders, $limit, $offset);
-
- return $this->db->createCommand($sql, $this->params)->queryAll();
- }
-
-
-
- protected function prepareKeys($models)
- {
- $keys = [];
- if ($this->key !== null) {
- foreach ($models as $model) {
- if (is_string($this->key)) {
- $keys[] = $model[$this->key];
- } else {
- $keys[] = call_user_func($this->key, $model);
- }
- }
-
- return $keys;
- } else {
- return array_keys($models);
- }
- }
-
-
-
- protected function prepareTotalCount()
- {
- return 0;
- }
- }
|