BaseDataProvider.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. namespace yii\data;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidArgumentException;
  11. /**
  12. * BaseDataProvider provides a base class that implements the [[DataProviderInterface]].
  13. *
  14. * For more details and usage information on BaseDataProvider, see the [guide article on data providers](guide:output-data-providers).
  15. *
  16. * @property-read int $count The number of data models in the current page.
  17. * @property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is
  18. * uniquely identified by the corresponding key value in this array.
  19. * @property array $models The list of data models in the current page.
  20. * @property Pagination|false $pagination The pagination object. If this is false, it means the pagination is
  21. * disabled. Note that the type of this property differs in getter and setter. See [[getPagination()]] and
  22. * [[setPagination()]] for details.
  23. * @property Sort|bool $sort The sorting object. If this is false, it means the sorting is disabled. Note that
  24. * the type of this property differs in getter and setter. See [[getSort()]] and [[setSort()]] for details.
  25. * @property int $totalCount Total number of possible data models.
  26. *
  27. * @author Qiang Xue <qiang.xue@gmail.com>
  28. * @since 2.0
  29. * @phpcs:disable Squiz.NamingConventions.ValidVariableName.PrivateNoUnderscore
  30. */
  31. abstract class BaseDataProvider extends Component implements DataProviderInterface
  32. {
  33. /**
  34. * @var int Number of data providers on the current page. Used to generate unique IDs.
  35. */
  36. private static $counter = 0;
  37. /**
  38. * @var string|null an ID that uniquely identifies the data provider among all data providers.
  39. * Generated automatically the following way in case it is not set:
  40. *
  41. * - First data provider ID is empty.
  42. * - Second and all subsequent data provider IDs are: "dp-1", "dp-2", etc.
  43. */
  44. public $id;
  45. private $_sort;
  46. private $_pagination;
  47. private $_keys;
  48. private $_models;
  49. private $_totalCount;
  50. /**
  51. * {@inheritdoc}
  52. */
  53. public function init()
  54. {
  55. parent::init();
  56. if ($this->id === null) {
  57. if (self::$counter > 0) {
  58. $this->id = 'dp-' . self::$counter;
  59. }
  60. self::$counter++;
  61. }
  62. }
  63. /**
  64. * Prepares the data models that will be made available in the current page.
  65. * @return array the available data models
  66. */
  67. abstract protected function prepareModels();
  68. /**
  69. * Prepares the keys associated with the currently available data models.
  70. * @param array $models the available data models
  71. * @return array the keys
  72. */
  73. abstract protected function prepareKeys($models);
  74. /**
  75. * Returns a value indicating the total number of data models in this data provider.
  76. * @return int total number of data models in this data provider.
  77. */
  78. abstract protected function prepareTotalCount();
  79. /**
  80. * Prepares the data models and keys.
  81. *
  82. * This method will prepare the data models and keys that can be retrieved via
  83. * [[getModels()]] and [[getKeys()]].
  84. *
  85. * This method will be implicitly called by [[getModels()]] and [[getKeys()]] if it has not been called before.
  86. *
  87. * @param bool $forcePrepare whether to force data preparation even if it has been done before.
  88. */
  89. public function prepare($forcePrepare = false)
  90. {
  91. if ($forcePrepare || $this->_models === null) {
  92. $this->_models = $this->prepareModels();
  93. }
  94. if ($forcePrepare || $this->_keys === null) {
  95. $this->_keys = $this->prepareKeys($this->_models);
  96. }
  97. }
  98. /**
  99. * Returns the data models in the current page.
  100. * @return array the list of data models in the current page.
  101. */
  102. public function getModels()
  103. {
  104. $this->prepare();
  105. return $this->_models;
  106. }
  107. /**
  108. * Sets the data models in the current page.
  109. * @param array $models the models in the current page
  110. */
  111. public function setModels($models)
  112. {
  113. $this->_models = $models;
  114. }
  115. /**
  116. * Returns the key values associated with the data models.
  117. * @return array the list of key values corresponding to [[models]]. Each data model in [[models]]
  118. * is uniquely identified by the corresponding key value in this array.
  119. */
  120. public function getKeys()
  121. {
  122. $this->prepare();
  123. return $this->_keys;
  124. }
  125. /**
  126. * Sets the key values associated with the data models.
  127. * @param array $keys the list of key values corresponding to [[models]].
  128. */
  129. public function setKeys($keys)
  130. {
  131. $this->_keys = $keys;
  132. }
  133. /**
  134. * Returns the number of data models in the current page.
  135. * @return int the number of data models in the current page.
  136. */
  137. public function getCount()
  138. {
  139. return count($this->getModels());
  140. }
  141. /**
  142. * Returns the total number of data models.
  143. * When [[pagination]] is false, this returns the same value as [[count]].
  144. * Otherwise, it will call [[prepareTotalCount()]] to get the count.
  145. * @return int total number of possible data models.
  146. */
  147. public function getTotalCount()
  148. {
  149. if ($this->getPagination() === false) {
  150. return $this->getCount();
  151. } elseif ($this->_totalCount === null) {
  152. $this->_totalCount = $this->prepareTotalCount();
  153. }
  154. return $this->_totalCount;
  155. }
  156. /**
  157. * Sets the total number of data models.
  158. * @param int $value the total number of data models.
  159. */
  160. public function setTotalCount($value)
  161. {
  162. $this->_totalCount = $value;
  163. }
  164. /**
  165. * Returns the pagination object used by this data provider.
  166. * Note that you should call [[prepare()]] or [[getModels()]] first to get correct values
  167. * of [[Pagination::totalCount]] and [[Pagination::pageCount]].
  168. * @return Pagination|false the pagination object. If this is false, it means the pagination is disabled.
  169. */
  170. public function getPagination()
  171. {
  172. if ($this->_pagination === null) {
  173. $this->setPagination([]);
  174. }
  175. return $this->_pagination;
  176. }
  177. /**
  178. * Sets the pagination for this data provider.
  179. * @param array|Pagination|bool $value the pagination to be used by this data provider.
  180. * This can be one of the following:
  181. *
  182. * - a configuration array for creating the pagination object. The "class" element defaults
  183. * to 'yii\data\Pagination'
  184. * - an instance of [[Pagination]] or its subclass
  185. * - false, if pagination needs to be disabled.
  186. *
  187. * @throws InvalidArgumentException
  188. */
  189. public function setPagination($value)
  190. {
  191. if (is_array($value)) {
  192. $config = ['class' => Pagination::className()];
  193. if ($this->id !== null) {
  194. $config['pageParam'] = $this->id . '-page';
  195. $config['pageSizeParam'] = $this->id . '-per-page';
  196. }
  197. $this->_pagination = Yii::createObject(array_merge($config, $value));
  198. } elseif ($value instanceof Pagination || $value === false) {
  199. $this->_pagination = $value;
  200. } else {
  201. throw new InvalidArgumentException('Only Pagination instance, configuration array or false is allowed.');
  202. }
  203. }
  204. /**
  205. * Returns the sorting object used by this data provider.
  206. * @return Sort|bool the sorting object. If this is false, it means the sorting is disabled.
  207. */
  208. public function getSort()
  209. {
  210. if ($this->_sort === null) {
  211. $this->setSort([]);
  212. }
  213. return $this->_sort;
  214. }
  215. /**
  216. * Sets the sort definition for this data provider.
  217. * @param array|Sort|bool $value the sort definition to be used by this data provider.
  218. * This can be one of the following:
  219. *
  220. * - a configuration array for creating the sort definition object. The "class" element defaults
  221. * to 'yii\data\Sort'
  222. * - an instance of [[Sort]] or its subclass
  223. * - false, if sorting needs to be disabled.
  224. *
  225. * @throws InvalidArgumentException
  226. */
  227. public function setSort($value)
  228. {
  229. if (is_array($value)) {
  230. $config = ['class' => Sort::className()];
  231. if ($this->id !== null) {
  232. $config['sortParam'] = $this->id . '-sort';
  233. }
  234. $this->_sort = Yii::createObject(array_merge($config, $value));
  235. } elseif ($value instanceof Sort || $value === false) {
  236. $this->_sort = $value;
  237. } else {
  238. throw new InvalidArgumentException('Only Sort instance, configuration array or false is allowed.');
  239. }
  240. }
  241. /**
  242. * Refreshes the data provider.
  243. * After calling this method, if [[getModels()]], [[getKeys()]] or [[getTotalCount()]] is called again,
  244. * they will re-execute the query and return the latest data available.
  245. */
  246. public function refresh()
  247. {
  248. $this->_totalCount = null;
  249. $this->_models = null;
  250. $this->_keys = null;
  251. }
  252. }