QueryTrait.php 12 KB

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