EagerLoader.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. namespace Cake\ORM;
  16. use Cake\Database\Statement\BufferedStatement;
  17. use Cake\Database\Statement\CallbackStatement;
  18. use Cake\ORM\Query;
  19. use Cake\ORM\Table;
  20. use Closure;
  21. /**
  22. * Exposes the methods for storing the associations that should be eager loaded
  23. * for a table once a query is provided and delegates the job of creating the
  24. * required joins and decorating the results so that those associations can be
  25. * part of the result set.
  26. */
  27. class EagerLoader {
  28. /**
  29. * Nested array describing the association to be fetched
  30. * and the options to apply for each of them, if any
  31. *
  32. * @var array
  33. */
  34. protected $_containments = [];
  35. /**
  36. * Contains a nested array with the compiled containments tree
  37. * This is a normalized version of the user provided containments array.
  38. *
  39. * @var array
  40. */
  41. protected $_normalized;
  42. /**
  43. * List of options accepted by associations in contain()
  44. * index by key for faster access
  45. *
  46. * @var array
  47. */
  48. protected $_containOptions = [
  49. 'associations' => 1,
  50. 'foreignKey' => 1,
  51. 'conditions' => 1,
  52. 'fields' => 1,
  53. 'sort' => 1,
  54. 'matching' => 1,
  55. 'queryBuilder' => 1
  56. ];
  57. /**
  58. * A list of associations that should be loaded with a separate query
  59. *
  60. * @var array
  61. */
  62. protected $_loadExternal = [];
  63. /**
  64. * Contains a list of the association names that are to be eagerly loaded
  65. *
  66. * @var array
  67. */
  68. protected $_aliasList = [];
  69. /**
  70. * Sets the list of associations that should be eagerly loaded along for a
  71. * specific table using when a query is provided. The list of associated tables
  72. * passed to this method must have been previously set as associations using the
  73. * Table API.
  74. *
  75. * Associations can be arbitrarily nested using dot notation or nested arrays,
  76. * this allows this object to calculate joins or any additional queries that
  77. * must be executed to bring the required associated data.
  78. *
  79. * Accepted options per passed association:
  80. *
  81. * - foreignKey: Used to set a different field to match both tables, if set to false
  82. * no join conditions will be generated automatically
  83. * - fields: An array with the fields that should be fetched from the association
  84. * - queryBuilder: Equivalent to passing a callable instead of an options array
  85. * - matching: Whether to inform the association class that it should filter the
  86. * main query by the results fetched by that class.
  87. *
  88. * @param array|string $associations list of table aliases to be queried.
  89. * When this method is called multiple times it will merge previous list with
  90. * the new one.
  91. * @return array|void
  92. */
  93. public function contain($associations = []) {
  94. if (empty($associations)) {
  95. return $this->_containments;
  96. }
  97. $associations = (array)$associations;
  98. $associations = $this->_reformatContain($associations, $this->_containments);
  99. $this->_normalized = $this->_loadExternal = null;
  100. return $this->_containments = $associations;
  101. }
  102. /**
  103. * Adds a new association to the list that will be used to filter the results of
  104. * any given query based on the results of finding records for that association.
  105. * You can pass a dot separated path of associations to this method as its first
  106. * parameter, this will translate in setting all those associations with the
  107. * `matching` option.
  108. *
  109. * @param string $assoc A single association or a dot separated path of associations.
  110. * @param callable $builder the callback function to be used for setting extra
  111. * options to the filtering query
  112. * @return array The resulting containments array
  113. */
  114. public function matching($assoc, callable $builder = null) {
  115. $assocs = explode('.', $assoc);
  116. $last = array_pop($assocs);
  117. $containments = [];
  118. $pointer =& $containments;
  119. foreach ($assocs as $name) {
  120. $pointer[$name] = ['matching' => true];
  121. $pointer =& $pointer[$name];
  122. }
  123. $pointer[$last] = ['queryBuilder' => $builder, 'matching' => true];
  124. return $this->contain($containments);
  125. }
  126. /**
  127. * Returns the fully normalized array of associations that should be eagerly
  128. * loaded for a table. The normalized array will restructure the original array
  129. * by sorting all associations under one key and special options under another.
  130. *
  131. * Additionally it will set an 'instance' key per association containing the
  132. * association instance from the corresponding source table
  133. *
  134. * @param \Cake\ORM\Table $repository The table containing the association that
  135. * will be normalized
  136. * @return array
  137. */
  138. public function normalized(Table $repository) {
  139. if ($this->_normalized !== null || empty($this->_containments)) {
  140. return (array)$this->_normalized;
  141. }
  142. $contain = [];
  143. foreach ($this->_containments as $alias => $options) {
  144. if (!empty($options['instance'])) {
  145. $contain = (array)$this->_containments;
  146. break;
  147. }
  148. $contain[$alias] = $this->_normalizeContain(
  149. $repository,
  150. $alias,
  151. $options,
  152. []
  153. );
  154. }
  155. return $this->_normalized = $contain;
  156. }
  157. /**
  158. * Formats the containments array so that associations are always set as keys
  159. * in the array. This function merges the original associations array with
  160. * the new associations provided
  161. *
  162. * @param array $associations user provided containments array
  163. * @param array $original The original containments array to merge
  164. * with the new one
  165. * @return array
  166. */
  167. protected function _reformatContain($associations, $original) {
  168. $result = $original;
  169. foreach ((array)$associations as $table => $options) {
  170. $pointer =& $result;
  171. if (is_int($table)) {
  172. $table = $options;
  173. $options = [];
  174. }
  175. if (isset($this->_containOptions[$table])) {
  176. $pointer[$table] = $options;
  177. continue;
  178. }
  179. if (strpos($table, '.')) {
  180. $path = explode('.', $table);
  181. $table = array_pop($path);
  182. foreach ($path as $t) {
  183. $pointer += [$t => []];
  184. $pointer =& $pointer[$t];
  185. }
  186. }
  187. if (is_array($options)) {
  188. $options = isset($options['config']) ?
  189. $options['config'] + $options['associations'] :
  190. $options;
  191. $options = $this->_reformatContain($options, []);
  192. }
  193. if ($options instanceof Closure) {
  194. $options = ['queryBuilder' => $options];
  195. }
  196. $pointer += [$table => []];
  197. $pointer[$table] = $options + $pointer[$table];
  198. }
  199. return $result;
  200. }
  201. /**
  202. * Modifies the passed query to apply joins or any other transformation required
  203. * in order to eager load the associations described in the `contain` array.
  204. * This method will not modify the query for loading external associations, i.e.
  205. * those that cannot be loaded without executing a separate query.
  206. *
  207. * @param \Cake\ORM\Query $query The query to be modified
  208. * @param \Cake\ORM\Table $repository The repository containing the associations
  209. * @param boolean $includeFields whether to append all fields from the associations
  210. * to the passed query. This can be overridden according to the settings defined
  211. * per association in the containments array
  212. * @return void
  213. */
  214. public function attachAssociations(Query $query, Table $repository, $includeFields) {
  215. if (empty($this->_containments)) {
  216. return;
  217. }
  218. foreach ($this->attachableAssociations($repository) as $options) {
  219. $config = $options['config'] + [
  220. 'aliasPath' => $options['aliasPath'],
  221. 'propertyPath' => $options['propertyPath'],
  222. 'includeFields' => $includeFields
  223. ];
  224. $options['instance']->attachTo($query, $config);
  225. }
  226. }
  227. /**
  228. * Returns an array with the associations that can be fetched using a single query,
  229. * the array keys are the association aliases and the values will contain an array
  230. * with the following keys:
  231. *
  232. * - instance: the association object instance
  233. * - config: the options set for fetching such association
  234. *
  235. * @param \Cake\ORM\Table $repository The table containing the associations to be
  236. * attached
  237. * @return array
  238. */
  239. public function attachableAssociations(Table $repository) {
  240. $contain = $this->normalized($repository);
  241. return $this->_resolveJoins($contain);
  242. }
  243. /**
  244. * Returns an array with the associations that need to be fetched using a
  245. * separate query, each array value will contain the following keys:
  246. *
  247. * - instance: the association object instance
  248. * - config: the options set for fetching such association
  249. *
  250. * @param \Cake\ORM\Table $repository The table containing the associations
  251. * to be loaded
  252. * @return array
  253. */
  254. public function externalAssociations(Table $repository) {
  255. if ($this->_loadExternal) {
  256. return $this->_loadExternal;
  257. }
  258. $contain = $this->normalized($repository);
  259. $this->_resolveJoins($contain);
  260. return $this->_loadExternal;
  261. }
  262. /**
  263. * Auxiliary function responsible for fully normalizing deep associations defined
  264. * using `contain()`
  265. *
  266. * @param Table $parent owning side of the association
  267. * @param string $alias name of the association to be loaded
  268. * @param array $options list of extra options to use for this association
  269. * @param array $paths An array with to values, the first one is a list of dot
  270. * separated strings representing associations that lead to this `$alias` in the
  271. * chain of associaitons to be loaded. The second value is the path to follow in
  272. * entities' properties to fetch a record of the corresponding association.
  273. * @return array normalized associations
  274. * @throws \InvalidArgumentException When containments refer to associations that do not exist.
  275. */
  276. protected function _normalizeContain(Table $parent, $alias, $options, $paths) {
  277. $defaults = $this->_containOptions;
  278. $instance = $parent->association($alias);
  279. if (!$instance) {
  280. throw new \InvalidArgumentException(
  281. sprintf('%s is not associated with %s', $parent->alias(), $alias)
  282. );
  283. }
  284. $paths += ['aliasPath' => '', 'propertyPath' => ''];
  285. $paths['aliasPath'] .= '.' . $alias;
  286. $paths['propertyPath'] .= '.' . $instance->property();
  287. $table = $instance->target();
  288. $extra = array_diff_key($options, $defaults);
  289. $config = [
  290. 'associations' => [],
  291. 'instance' => $instance,
  292. 'config' => array_diff_key($options, $extra),
  293. 'aliasPath' => trim($paths['aliasPath'], '.'),
  294. 'propertyPath' => trim($paths['propertyPath'], '.'),
  295. ];
  296. $config['canBeJoined'] = $instance->canBeJoined($config['config']);
  297. if ($config['canBeJoined'] && !empty($this->_aliasList[$alias])) {
  298. $config['canBeJoined'] = false;
  299. $config['config']['strategy'] = $instance::STRATEGY_SELECT;
  300. }
  301. $this->_aliasList[$alias][] = $paths['aliasPath'];
  302. foreach ($extra as $t => $assoc) {
  303. $config['associations'][$t] = $this->_normalizeContain($table, $t, $assoc, $paths);
  304. }
  305. return $config;
  306. }
  307. /**
  308. * Helper function used to compile a list of all associations that can be
  309. * joined in the query.
  310. *
  311. * @param array $associations list of associations for $source
  312. * @return array
  313. */
  314. protected function _resolveJoins($associations) {
  315. $result = [];
  316. foreach ($associations as $table => $options) {
  317. if ($options['canBeJoined']) {
  318. $result[$table] = $options;
  319. $result += $this->_resolveJoins($options['associations']);
  320. } else {
  321. $this->_loadExternal[] = $options;
  322. }
  323. }
  324. return $result;
  325. }
  326. /**
  327. * Decorates the passed statement object in order to inject data form associations
  328. * that cannot be joined directly.
  329. *
  330. * @param \Cake\ORM\Query $query The query for which to eager load external
  331. * associations
  332. * @param \Cake\Database\StatementInterface $statement The statement created after executing the $query
  333. * @return CallbackStatement $statement modified statement with extra loaders
  334. */
  335. public function loadExternal($query, $statement) {
  336. $external = $this->externalAssociations($query->repository());
  337. if (empty($external)) {
  338. return $statement;
  339. }
  340. $driver = $query->connection()->driver();
  341. list($collected, $statement) = $this->_collectKeys($external, $query, $statement);
  342. foreach ($external as $meta) {
  343. $contain = $meta['associations'];
  344. $alias = $meta['instance']->source()->alias();
  345. $requiresKeys = $meta['instance']->requiresKeys($meta['config']);
  346. if ($requiresKeys && empty($collected[$alias])) {
  347. continue;
  348. }
  349. $keys = isset($collected[$alias]) ? $collected[$alias] : null;
  350. $f = $meta['instance']->eagerLoader(
  351. $meta['config'] + [
  352. 'query' => $query,
  353. 'contain' => $contain,
  354. 'keys' => $keys,
  355. 'nestKey' => $meta['aliasPath']
  356. ]
  357. );
  358. $statement = new CallbackStatement($statement, $driver, $f);
  359. }
  360. return $statement;
  361. }
  362. /**
  363. * Helper function used to return the keys from the query records that will be used
  364. * to eagerly load associations.
  365. *
  366. * @param array $external the list of external associations to be loaded
  367. * @param \Cake\ORM\Query $query The query from which the results where generated
  368. * @param BufferedStatement $statement
  369. * @return array
  370. */
  371. protected function _collectKeys($external, $query, $statement) {
  372. $collectKeys = [];
  373. foreach ($external as $meta) {
  374. if (!$meta['instance']->requiresKeys($meta['config'])) {
  375. continue;
  376. }
  377. $source = $meta['instance']->source();
  378. $keys = $meta['instance']->type() === $meta['instance']::MANY_TO_ONE ?
  379. (array)$meta['instance']->foreignKey() :
  380. (array)$source->primaryKey();
  381. $alias = $source->alias();
  382. $pkFields = [];
  383. foreach ($keys as $key) {
  384. $pkFields[] = key($query->aliasField($key, $alias));
  385. }
  386. $collectKeys[$alias] = [$alias, $pkFields, count($pkFields) === 1];
  387. }
  388. if (empty($collectKeys)) {
  389. return [[], $statement];
  390. }
  391. if (!($statement instanceof BufferedStatement)) {
  392. $statement = new BufferedStatement($statement, $query->connection()->driver());
  393. }
  394. return [$this->_groupKeys($statement, $collectKeys), $statement];
  395. }
  396. /**
  397. * Helper function used to iterate an statement and extract the columns
  398. * defined in $collectKeys
  399. *
  400. * @param \Cake\Database\StatementInterface $statement
  401. * @param array $collectKeys
  402. * @return array
  403. */
  404. protected function _groupKeys($statement, $collectKeys) {
  405. $keys = [];
  406. while ($result = $statement->fetch('assoc')) {
  407. foreach ($collectKeys as $parts) {
  408. if ($parts[2]) {
  409. $keys[$parts[0]][] = $result[$parts[1][0]];
  410. continue;
  411. }
  412. $collected = [];
  413. foreach ($parts[1] as $key) {
  414. $collected[] = $result[$key];
  415. }
  416. $keys[$parts[0]][] = $collected;
  417. }
  418. }
  419. $statement->rewind();
  420. return $keys;
  421. }
  422. }