QueryTrait.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Datasource;
  16. use Cake\Collection\Iterator\MapReduce;
  17. use Cake\Datasource\QueryCacher;
  18. use Cake\Datasource\RepositoryInterface;
  19. use Cake\Datasource\ResultSetDecorator;
  20. use Cake\Event\Event;
  21. /**
  22. * Contains the characteristics for an object that is attached to a repository and
  23. * can retrieve results based on any criteria.
  24. *
  25. */
  26. trait QueryTrait {
  27. /**
  28. * Instance of a table object this query is bound to
  29. *
  30. * @var \Cake\Datasource\RepositoryInterface
  31. */
  32. protected $_repository;
  33. /**
  34. * A ResultSet.
  35. *
  36. * When set, query execution will be bypassed.
  37. *
  38. * @var \Cake\Datasource\ResultSetDecorator
  39. * @see setResult()
  40. */
  41. protected $_results;
  42. /**
  43. * List of map-reduce routines that should be applied over the query
  44. * result
  45. *
  46. * @var array
  47. */
  48. protected $_mapReduce = [];
  49. /**
  50. * List of formatter classes or callbacks that will post-process the
  51. * results when fetched
  52. *
  53. * @var array
  54. */
  55. protected $_formatters = [];
  56. /**
  57. * A query cacher instance if this query has caching enabled.
  58. *
  59. * @var \Cake\Datasource\QueryCacher
  60. */
  61. protected $_cache;
  62. /**
  63. * Holds any custom options passed using applyOptions that could not be processed
  64. * by any method in this class.
  65. *
  66. * @var array
  67. */
  68. protected $_options = [];
  69. /**
  70. * Whether the query is standalone or the product of an eager load operation.
  71. *
  72. * @var bool
  73. */
  74. protected $_eagerLoaded = false;
  75. /**
  76. * Returns the default table object that will be used by this query,
  77. * that is, the table that will appear in the from clause.
  78. *
  79. * When called with a Table argument, the default table object will be set
  80. * and this query object will be returned for chaining.
  81. *
  82. * @param \Cake\Datasource\RepositoryInterface $table The default table object to use
  83. * @return \Cake\Datasource\RepositoryInterface|\Cake\ORM\Query
  84. */
  85. public function repository(RepositoryInterface $table = null) {
  86. if ($table === null) {
  87. return $this->_repository;
  88. }
  89. $this->_repository = $table;
  90. return $this;
  91. }
  92. /**
  93. * Set the result set for a query.
  94. *
  95. * Setting the resultset of a query will make execute() a no-op. Instead
  96. * of executing the SQL query and fetching results, the ResultSet provided to this
  97. * method will be returned.
  98. *
  99. * This method is most useful when combined with results stored in a persistent cache.
  100. *
  101. * @param \Cake\ORM\ResultSet $results The results this query should return.
  102. * @return \Cake\ORM\Query The query instance.
  103. */
  104. public function setResult($results) {
  105. $this->_results = $results;
  106. return $this;
  107. }
  108. /**
  109. * Executes this query and returns a results iterator. This function is required
  110. * for implementing the IteratorAggregate interface and allows the query to be
  111. * iterated without having to call execute() manually, thus making it look like
  112. * a result set instead of the query itself.
  113. *
  114. * @return \Iterator
  115. */
  116. public function getIterator() {
  117. return $this->all();
  118. }
  119. /**
  120. * Enable result caching for this query.
  121. *
  122. * If a query has caching enabled, it will do the following when executed:
  123. *
  124. * - Check the cache for $key. If there are results no SQL will be executed.
  125. * Instead the cached results will be returned.
  126. * - When the cached data is stale/missing the result set will be cached as the query
  127. * is executed.
  128. *
  129. * ## Usage
  130. *
  131. * {{{
  132. * // Simple string key + config
  133. * $query->cache('my_key', 'db_results');
  134. *
  135. * // Function to generate key.
  136. * $query->cache(function($q) {
  137. * $key = serialize($q->clause('select'));
  138. * $key .= serialize($q->clause('where'));
  139. * return md5($key);
  140. * });
  141. *
  142. * // Using a pre-built cache engine.
  143. * $query->cache('my_key', $engine);
  144. *
  145. * // Disable caching
  146. * $query->cache(false);
  147. * }}}
  148. *
  149. * @param false|string|\Closure $key Either the cache key or a function to generate the cache key.
  150. * When using a function, this query instance will be supplied as an argument.
  151. * @param string|\Cake\Cache\CacheEngine $config Either the name of the cache config to use, or
  152. * a cache config instance.
  153. * @return \Cake\Datasource\QueryTrait This same object
  154. */
  155. public function cache($key, $config = 'default') {
  156. if ($key === false) {
  157. $this->_cache = null;
  158. return $this;
  159. }
  160. $this->_cache = new QueryCacher($key, $config);
  161. return $this;
  162. }
  163. /**
  164. * Sets the query instance to be the eager loaded query. If no argument is
  165. * passed, the current configured query `_eagerLoaded` value is returned.
  166. *
  167. * @param bool $value Whether or not to eager load.
  168. * @return \Cake\ORM\Query
  169. */
  170. public function eagerLoaded($value = null) {
  171. if ($value === null) {
  172. return $this->_eagerLoaded;
  173. }
  174. $this->_eagerLoaded = $value;
  175. return $this;
  176. }
  177. /**
  178. * Fetch the results for this query.
  179. *
  180. * Will return either the results set through setResult(), or execute this query
  181. * and return the ResultSetDecorator object ready for streaming of results.
  182. *
  183. * ResultSetDecorator is a travesable object that implements the methods found
  184. * on Cake\Collection\Collection.
  185. *
  186. * @return \Cake\DataSource\ResultSetDecorator
  187. */
  188. public function all() {
  189. if (isset($this->_results)) {
  190. return $this->_results;
  191. }
  192. $table = $this->repository();
  193. $table->dispatchEvent('Model.beforeFind', [$this, $this->_options, !$this->eagerLoaded()]);
  194. if (isset($this->_results)) {
  195. return $this->_results;
  196. }
  197. if ($this->_cache) {
  198. $results = $this->_cache->fetch($this);
  199. }
  200. if (!isset($results)) {
  201. $results = $this->_decorateResults($this->_execute());
  202. if ($this->_cache) {
  203. $this->_cache->store($this, $results);
  204. }
  205. }
  206. $this->_results = $results;
  207. return $this->_results;
  208. }
  209. /**
  210. * Returns an array representation of the results after executing the query.
  211. *
  212. * @return array
  213. */
  214. public function toArray() {
  215. return $this->all()->toArray();
  216. }
  217. /**
  218. * Register a new MapReduce routine to be executed on top of the database results
  219. * Both the mapper and caller callable should be invokable objects.
  220. *
  221. * The MapReduce routing will only be run when the query is executed and the first
  222. * result is attempted to be fetched.
  223. *
  224. * If the first argument is set to null, it will return the list of previously
  225. * registered map reduce routines.
  226. *
  227. * If the third argument is set to true, it will erase previous map reducers
  228. * and replace it with the arguments passed.
  229. *
  230. * @param callable $mapper The mapper callable.
  231. * @param callable $reducer The reducing function.
  232. * @param bool $overwrite Set to true to overwrite existing map + reduce functions.
  233. * @return \Cake\Datasource\QueryTrait|array
  234. * @see \Cake\Collection\Iterator\MapReduce for details on how to use emit data to the map reducer.
  235. */
  236. public function mapReduce(callable $mapper = null, callable $reducer = null, $overwrite = false) {
  237. if ($overwrite) {
  238. $this->_mapReduce = [];
  239. }
  240. if ($mapper === null) {
  241. return $this->_mapReduce;
  242. }
  243. $this->_mapReduce[] = compact('mapper', 'reducer');
  244. return $this;
  245. }
  246. /**
  247. * Registers a new formatter callback function that is to be executed when trying
  248. * to fetch the results from the database.
  249. *
  250. * Formatting callbacks will get a first parameter, a `ResultSetDecorator`, that
  251. * can be traversed and modified at will. As for the second parameter, the
  252. * formatting callback will receive this query instance.
  253. *
  254. * Callbacks are required to return an iterator object, which will be used as
  255. * the return value for this query's result. Formatter functions are applied
  256. * after all the `MapReduce` routines for this query have been executed.
  257. *
  258. * If the first argument is set to null, it will return the list of previously
  259. * registered map reduce routines.
  260. *
  261. * If the second argument is set to true, it will erase previous formatters
  262. * and replace them with the passed first argument.
  263. *
  264. * ### Example:
  265. *
  266. * {{{
  267. * // Return all results from the table indexed by id
  268. * $query->select(['id', 'name'])->formatResults(function($results, $query) {
  269. * return $results->indexBy('id');
  270. * });
  271. *
  272. * // Add a new column to the ResultSet
  273. * $query->select(['name', 'birth_date'])->formatResults(function($results, $query) {
  274. * return $results->map(function($row) {
  275. * $row['age'] = $row['birth_date']->diff(new DateTime)->y;
  276. * return $row;
  277. * });
  278. * });
  279. * }}}
  280. *
  281. * @param callable $formatter The formatting callable.
  282. * @param bool|int $mode Whether or not to overwrite, append or prepend the formatter.
  283. * @return \Cake\Datasource\QueryTrait|array
  284. */
  285. public function formatResults(callable $formatter = null, $mode = 0) {
  286. if ($mode === self::OVERWRITE) {
  287. $this->_formatters = [];
  288. }
  289. if ($formatter === null) {
  290. return $this->_formatters;
  291. }
  292. if ($mode === self::PREPEND) {
  293. array_unshift($this->_formatters, $formatter);
  294. return $this;
  295. }
  296. $this->_formatters[] = $formatter;
  297. return $this;
  298. }
  299. /**
  300. * Returns the first result out of executing this query, if the query has not been
  301. * executed before, it will set the limit clause to 1 for performance reasons.
  302. *
  303. * ### Example:
  304. *
  305. * `$singleUser = $query->select(['id', 'username'])->first();`
  306. *
  307. * @return mixed the first result from the ResultSet
  308. */
  309. public function first() {
  310. if ($this->_dirty) {
  311. $this->limit(1);
  312. }
  313. return $this->all()->first();
  314. }
  315. /**
  316. * Returns an array with the custom options that were applied to this query
  317. * and that were not already processed by another method in this class.
  318. *
  319. * ###Example:
  320. *
  321. * {{{
  322. * $query->applyOptions(['doABarrelRoll' => true, 'fields' => ['id', 'name']);
  323. * $query->getOptions(); // Returns ['doABarrelRoll' => true]
  324. * }}}
  325. *
  326. * @see \Cake\ORM\Query::applyOptions() to read about the options that will
  327. * be processed by this class and not returned by this function
  328. * @return array
  329. */
  330. public function getOptions() {
  331. return $this->_options;
  332. }
  333. /**
  334. * Enables calling methods from the result set as if they were from this class
  335. *
  336. * @param string $method the method to call
  337. * @param array $arguments list of arguments for the method to call
  338. * @return mixed
  339. * @throws \BadMethodCallException if no such method exists in result set
  340. */
  341. public function __call($method, $arguments) {
  342. $resultSetClass = $this->_decoratorClass();
  343. if (in_array($method, get_class_methods($resultSetClass))) {
  344. $results = $this->all();
  345. return call_user_func_array([$results, $method], $arguments);
  346. }
  347. throw new \BadMethodCallException(
  348. sprintf('Unknown method "%s"', $method)
  349. );
  350. }
  351. /**
  352. * Populates or adds parts to current query clauses using an array.
  353. * This is handy for passing all query clauses at once.
  354. *
  355. * @param array $options the options to be applied
  356. * @return \Cake\Datasource\QueryTrait this object
  357. */
  358. abstract public function applyOptions(array $options);
  359. /**
  360. * Executes this query and returns a traversable object containing the results
  361. *
  362. * @return \Traversable
  363. */
  364. abstract protected function _execute();
  365. /**
  366. * Decorates the results iterator with MapReduce routines and formatters
  367. *
  368. * @param \Traversable $result Original results
  369. * @return \Cake\Datasource\ResultSetDecorator
  370. */
  371. protected function _decorateResults($result) {
  372. $decorator = $this->_decoratorClass();
  373. foreach ($this->_mapReduce as $functions) {
  374. $result = new MapReduce($result, $functions['mapper'], $functions['reducer']);
  375. }
  376. if (!empty($this->_mapReduce)) {
  377. $result = new $decorator($result);
  378. }
  379. foreach ($this->_formatters as $formatter) {
  380. $result = $formatter($result, $this);
  381. }
  382. if (!empty($this->_formatters) && !($result instanceof $decorator)) {
  383. $result = new $decorator($result);
  384. }
  385. return $result;
  386. }
  387. /**
  388. * Returns the name of the class to be used for decorating results
  389. *
  390. * @return string
  391. */
  392. protected function _decoratorClass() {
  393. return 'Cake\Datasource\ResultSetDecorator';
  394. }
  395. }