ActiveDataProvider.php 6.17 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\data;

10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\db\Query;
13
use yii\db\ActiveQuery;
14
use yii\db\Connection;
15 16

/**
17
 * ActiveDataProvider implements a data provider based on [[Query]] and [[ActiveQuery]].
18
 *
19
 * ActiveDataProvider provides data by performing DB queries using [[query]].
20
 *
21
 * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
22 23 24 25 26 27 28 29 30 31 32 33 34
 *
 * ~~~
 * $provider = new ActiveDataProvider(array(
 *     'query' => Post::find(),
 *     'pagination' => array(
 *         'pageSize' => 20,
 *     ),
 * ));
 *
 * // get the posts in the current page
 * $posts = $provider->getItems();
 * ~~~
 *
35 36 37
 * And the following example shows how to use ActiveDataProvider without ActiveRecord:
 *
 * ~~~
38
 * $query = new Query;
39
 * $provider = new ActiveDataProvider(array(
40
 *     'query' => $query->from('tbl_post'),
41 42 43 44 45 46 47 48 49
 *     'pagination' => array(
 *         'pageSize' => 20,
 *     ),
 * ));
 *
 * // get the posts in the current page
 * $posts = $provider->getItems();
 * ~~~
 *
50 51 52 53 54 55
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ActiveDataProvider extends DataProvider
{
	/**
Qiang Xue committed
56
	 * @var Query the query that is used to fetch data items and [[totalCount]]
57 58 59 60
	 * if it is not explicitly set.
	 */
	public $query;
	/**
61 62 63 64 65 66 67 68 69
	 * @var string|callable the column that is used as the key of the data items.
	 * This can be either a column name, or a callable that returns the key value of a given data item.
	 *
	 * If this is not set, the following rules will be used to determine the keys of the data items:
	 *
	 * - If [[query]] is an [[ActiveQuery]] instance, the primary keys of [[ActiveQuery::modelClass]] will be used.
	 * - Otherwise, the keys of the [[items]] array will be used.
	 *
	 * @see getKeys()
70
	 */
71
	public $key;
72 73 74 75 76
	/**
	 * @var Connection|string the DB connection object or the application component ID of the DB connection.
	 * If not set, the default DB connection will be used.
	 */
	public $db;
77 78 79 80 81

	private $_items;
	private $_keys;
	private $_count;

82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
	/**
	 * Initializes the DbCache component.
	 * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
	 * @throws InvalidConfigException if [[db]] is invalid.
	 */
	public function init()
	{
		parent::init();
		if (is_string($this->db)) {
			$this->db = Yii::$app->getComponent($this->db);
			if (!$this->db instanceof Connection) {
				throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
			}
		}
	}

98 99
	/**
	 * Returns the number of data items in the current page.
100
	 * This is equivalent to `count($provider->items)`.
Qiang Xue committed
101
	 * When [[pagination]] is false, this is the same as [[totalCount]].
102 103 104 105
	 * @param boolean $refresh whether to recalculate the item count. If true,
	 * this will cause re-fetching of [[items]].
	 * @return integer the number of data items in the current page.
	 */
Qiang Xue committed
106
	public function getCount($refresh = false)
107 108 109 110 111 112
	{
		return count($this->getItems($refresh));
	}

	/**
	 * Returns the total number of data items.
Qiang Xue committed
113 114
	 * When [[pagination]] is false, this returns the same value as [[count]].
	 * If [[totalCount]] is not explicitly set, it will be calculated
115 116 117 118 119
	 * using [[query]] with a COUNT query.
	 * @param boolean $refresh whether to recalculate the item count
	 * @return integer total number of possible data items.
	 * @throws InvalidConfigException
	 */
Qiang Xue committed
120
	public function getTotalCount($refresh = false)
121 122
	{
		if ($this->getPagination() === false) {
Qiang Xue committed
123
			return $this->getCount($refresh);
124
		} elseif ($this->_count === null || $refresh) {
125 126
			if (!$this->query instanceof Query) {
				throw new InvalidConfigException('The "query" property must be an instance of Query or its subclass.');
127 128
			}
			$query = clone $this->query;
129
			$this->_count = $query->limit(-1)->offset(-1)->count('*', $this->db);
130 131 132 133 134 135 136 137
		}
		return $this->_count;
	}

	/**
	 * Sets the total number of data items.
	 * @param integer $value the total number of data items.
	 */
Qiang Xue committed
138
	public function setTotalCount($value)
139 140 141 142 143 144 145 146 147 148 149 150 151
	{
		$this->_count = $value;
	}

	/**
	 * Returns the data items in the current page.
	 * @param boolean $refresh whether to re-fetch the data items.
	 * @return array the list of data items in the current page.
	 * @throws InvalidConfigException
	 */
	public function getItems($refresh = false)
	{
		if ($this->_items === null || $refresh) {
152 153
			if (!$this->query instanceof Query) {
				throw new InvalidConfigException('The "query" property must be an instance of Query or its subclass.');
154 155
			}
			if (($pagination = $this->getPagination()) !== false) {
Qiang Xue committed
156
				$pagination->totalCount = $this->getTotalCount();
157 158 159 160 161
				$this->query->limit($pagination->getLimit())->offset($pagination->getOffset());
			}
			if (($sort = $this->getSort()) !== false) {
				$this->query->orderBy($sort->getOrders());
			}
162
			$this->_items = $this->query->all($this->db);
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
		}
		return $this->_items;
	}

	/**
	 * Returns the key values associated with the data items.
	 * @param boolean $refresh whether to re-fetch the data items and re-calculate the keys
	 * @return array the list of key values corresponding to [[items]]. Each data item in [[items]]
	 * is uniquely identified by the corresponding key value in this array.
	 */
	public function getKeys($refresh = false)
	{
		if ($this->_keys === null || $refresh) {
			$this->_keys = array();
			$items = $this->getItems($refresh);
178 179 180 181 182 183 184 185 186
			if ($this->key !== null) {
				foreach ($items as $item) {
					if (is_string($this->key)) {
						$this->_keys[] = $item[$this->key];
					} else {
						$this->_keys[] = call_user_func($this->key, $item);
					}
				}
			} elseif ($this->query instanceof ActiveQuery) {
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
				/** @var \yii\db\ActiveRecord $class */
				$class = $this->query->modelClass;
				$pks = $class::primaryKey();
				if (count($pks) === 1) {
					$pk = $pks[0];
					foreach ($items as $item) {
						$this->_keys[] = $item[$pk];
					}
				} else {
					foreach ($items as $item) {
						$keys = array();
						foreach ($pks as $pk) {
							$keys[] = $item[$pk];
						}
						$this->_keys[] = json_encode($keys);
					}
				}
			} else {
205
				$this->_keys = array_keys($items);
206 207 208 209 210
			}
		}
		return $this->_keys;
	}
}