AssociationCollection.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\ORM;
  16. use ArrayIterator;
  17. use Cake\Datasource\EntityInterface;
  18. use Cake\ORM\Locator\LocatorAwareTrait;
  19. use Cake\ORM\Locator\LocatorInterface;
  20. use InvalidArgumentException;
  21. use IteratorAggregate;
  22. /**
  23. * A container/collection for association classes.
  24. *
  25. * Contains methods for managing associations, and
  26. * ordering operations around saving and deleting.
  27. */
  28. class AssociationCollection implements IteratorAggregate
  29. {
  30. use AssociationsNormalizerTrait;
  31. use LocatorAwareTrait;
  32. /**
  33. * Stored associations
  34. *
  35. * @var \Cake\ORM\Association[]
  36. */
  37. protected $_items = [];
  38. /**
  39. * Constructor.
  40. *
  41. * Sets the default table locator for associations.
  42. * If no locator is provided, the global one will be used.
  43. *
  44. * @param \Cake\ORM\Locator\LocatorInterface|null $tableLocator Table locator instance.
  45. */
  46. public function __construct(LocatorInterface $tableLocator = null)
  47. {
  48. if ($tableLocator !== null) {
  49. $this->_tableLocator = $tableLocator;
  50. }
  51. }
  52. /**
  53. * Add an association to the collection
  54. *
  55. * If the alias added contains a `.` the part preceding the `.` will be dropped.
  56. * This makes using plugins simpler as the Plugin.Class syntax is frequently used.
  57. *
  58. * @param string $alias The association alias
  59. * @param \Cake\ORM\Association $association The association to add.
  60. * @return \Cake\ORM\Association The association object being added.
  61. */
  62. public function add($alias, Association $association)
  63. {
  64. list(, $alias) = pluginSplit($alias);
  65. return $this->_items[strtolower($alias)] = $association;
  66. }
  67. /**
  68. * Creates and adds the Association object to this collection.
  69. *
  70. * @param string $className The name of association class.
  71. * @param string $associated The alias for the target table.
  72. * @param array $options List of options to configure the association definition.
  73. * @return \Cake\ORM\Association
  74. * @throws \InvalidArgumentException
  75. */
  76. public function load($className, $associated, array $options = [])
  77. {
  78. $options += [
  79. 'tableLocator' => $this->getTableLocator(),
  80. ];
  81. $association = new $className($associated, $options);
  82. if (!$association instanceof Association) {
  83. $message = sprintf('The association must extend `%s` class, `%s` given.', Association::class, get_class($association));
  84. throw new InvalidArgumentException($message);
  85. }
  86. return $this->add($association->getName(), $association);
  87. }
  88. /**
  89. * Fetch an attached association by name.
  90. *
  91. * @param string $alias The association alias to get.
  92. * @return \Cake\ORM\Association|null Either the association or null.
  93. */
  94. public function get($alias)
  95. {
  96. $alias = strtolower($alias);
  97. if (isset($this->_items[$alias])) {
  98. return $this->_items[$alias];
  99. }
  100. return null;
  101. }
  102. /**
  103. * Fetch an association by property name.
  104. *
  105. * @param string $prop The property to find an association by.
  106. * @return \Cake\ORM\Association|null Either the association or null.
  107. */
  108. public function getByProperty($prop)
  109. {
  110. foreach ($this->_items as $assoc) {
  111. if ($assoc->getProperty() === $prop) {
  112. return $assoc;
  113. }
  114. }
  115. return null;
  116. }
  117. /**
  118. * Check for an attached association by name.
  119. *
  120. * @param string $alias The association alias to get.
  121. * @return bool Whether or not the association exists.
  122. */
  123. public function has($alias)
  124. {
  125. return isset($this->_items[strtolower($alias)]);
  126. }
  127. /**
  128. * Get the names of all the associations in the collection.
  129. *
  130. * @return string[]
  131. */
  132. public function keys()
  133. {
  134. return array_keys($this->_items);
  135. }
  136. /**
  137. * Get an array of associations matching a specific type.
  138. *
  139. * @param string|array $class The type of associations you want.
  140. * For example 'BelongsTo' or array like ['BelongsTo', 'HasOne']
  141. * @return array An array of Association objects.
  142. * @deprecated 3.5.3 Use getByType() instead.
  143. */
  144. public function type($class)
  145. {
  146. deprecationWarning(
  147. 'AssociationCollection::type() is deprecated. ' .
  148. 'Use getByType() instead.'
  149. );
  150. return $this->getByType($class);
  151. }
  152. /**
  153. * Get an array of associations matching a specific type.
  154. *
  155. * @param string|string[] $class The type of associations you want.
  156. * For example 'BelongsTo' or array like ['BelongsTo', 'HasOne']
  157. * @return array An array of Association objects.
  158. * @since 3.5.3
  159. */
  160. public function getByType($class)
  161. {
  162. $class = array_map('strtolower', (array)$class);
  163. $out = array_filter($this->_items, function ($assoc) use ($class) {
  164. list(, $name) = namespaceSplit(get_class($assoc));
  165. return in_array(strtolower($name), $class, true);
  166. });
  167. return array_values($out);
  168. }
  169. /**
  170. * Drop/remove an association.
  171. *
  172. * Once removed the association will not longer be reachable
  173. *
  174. * @param string $alias The alias name.
  175. * @return void
  176. */
  177. public function remove($alias)
  178. {
  179. unset($this->_items[strtolower($alias)]);
  180. }
  181. /**
  182. * Remove all registered associations.
  183. *
  184. * Once removed associations will not longer be reachable
  185. *
  186. * @return void
  187. */
  188. public function removeAll()
  189. {
  190. foreach ($this->_items as $alias => $object) {
  191. $this->remove($alias);
  192. }
  193. }
  194. /**
  195. * Save all the associations that are parents of the given entity.
  196. *
  197. * Parent associations include any association where the given table
  198. * is the owning side.
  199. *
  200. * @param \Cake\ORM\Table $table The table entity is for.
  201. * @param \Cake\Datasource\EntityInterface $entity The entity to save associated data for.
  202. * @param array $associations The list of associations to save parents from.
  203. * associations not in this list will not be saved.
  204. * @param array $options The options for the save operation.
  205. * @return bool Success
  206. */
  207. public function saveParents(Table $table, EntityInterface $entity, $associations, array $options = [])
  208. {
  209. if (empty($associations)) {
  210. return true;
  211. }
  212. return $this->_saveAssociations($table, $entity, $associations, $options, false);
  213. }
  214. /**
  215. * Save all the associations that are children of the given entity.
  216. *
  217. * Child associations include any association where the given table
  218. * is not the owning side.
  219. *
  220. * @param \Cake\ORM\Table $table The table entity is for.
  221. * @param \Cake\Datasource\EntityInterface $entity The entity to save associated data for.
  222. * @param array $associations The list of associations to save children from.
  223. * associations not in this list will not be saved.
  224. * @param array $options The options for the save operation.
  225. * @return bool Success
  226. */
  227. public function saveChildren(Table $table, EntityInterface $entity, array $associations, array $options)
  228. {
  229. if (empty($associations)) {
  230. return true;
  231. }
  232. return $this->_saveAssociations($table, $entity, $associations, $options, true);
  233. }
  234. /**
  235. * Helper method for saving an association's data.
  236. *
  237. * @param \Cake\ORM\Table $table The table the save is currently operating on
  238. * @param \Cake\Datasource\EntityInterface $entity The entity to save
  239. * @param array $associations Array of associations to save.
  240. * @param array $options Original options
  241. * @param bool $owningSide Compared with association classes'
  242. * isOwningSide method.
  243. * @return bool Success
  244. * @throws \InvalidArgumentException When an unknown alias is used.
  245. */
  246. protected function _saveAssociations($table, $entity, $associations, $options, $owningSide)
  247. {
  248. unset($options['associated']);
  249. foreach ($associations as $alias => $nested) {
  250. if (is_int($alias)) {
  251. $alias = $nested;
  252. $nested = [];
  253. }
  254. $relation = $this->get($alias);
  255. if (!$relation) {
  256. $msg = sprintf(
  257. 'Cannot save %s, it is not associated to %s',
  258. $alias,
  259. $table->getAlias()
  260. );
  261. throw new InvalidArgumentException($msg);
  262. }
  263. if ($relation->isOwningSide($table) !== $owningSide) {
  264. continue;
  265. }
  266. if (!$this->_save($relation, $entity, $nested, $options)) {
  267. return false;
  268. }
  269. }
  270. return true;
  271. }
  272. /**
  273. * Helper method for saving an association's data.
  274. *
  275. * @param \Cake\ORM\Association $association The association object to save with.
  276. * @param \Cake\Datasource\EntityInterface $entity The entity to save
  277. * @param array $nested Options for deeper associations
  278. * @param array $options Original options
  279. * @return bool Success
  280. */
  281. protected function _save($association, $entity, $nested, $options)
  282. {
  283. if (!$entity->isDirty($association->getProperty())) {
  284. return true;
  285. }
  286. if (!empty($nested)) {
  287. $options = (array)$nested + $options;
  288. }
  289. return (bool)$association->saveAssociated($entity, $options);
  290. }
  291. /**
  292. * Cascade a delete across the various associations.
  293. * Cascade first across associations for which cascadeCallbacks is true.
  294. *
  295. * @param \Cake\Datasource\EntityInterface $entity The entity to delete associations for.
  296. * @param array $options The options used in the delete operation.
  297. * @return void
  298. */
  299. public function cascadeDelete(EntityInterface $entity, array $options)
  300. {
  301. $noCascade = $this->_getNoCascadeItems($entity, $options);
  302. foreach ($noCascade as $assoc) {
  303. $assoc->cascadeDelete($entity, $options);
  304. }
  305. }
  306. /**
  307. * Returns items that have no cascade callback.
  308. *
  309. * @param \Cake\Datasource\EntityInterface $entity The entity to delete associations for.
  310. * @param array $options The options used in the delete operation.
  311. * @return \Cake\ORM\Association[]
  312. */
  313. protected function _getNoCascadeItems($entity, $options)
  314. {
  315. $noCascade = [];
  316. foreach ($this->_items as $assoc) {
  317. if (!$assoc->getCascadeCallbacks()) {
  318. $noCascade[] = $assoc;
  319. continue;
  320. }
  321. $assoc->cascadeDelete($entity, $options);
  322. }
  323. return $noCascade;
  324. }
  325. /**
  326. * Returns an associative array of association names out a mixed
  327. * array. If true is passed, then it returns all association names
  328. * in this collection.
  329. *
  330. * @param bool|array $keys the list of association names to normalize
  331. * @return array
  332. */
  333. public function normalizeKeys($keys)
  334. {
  335. if ($keys === true) {
  336. $keys = $this->keys();
  337. }
  338. if (empty($keys)) {
  339. return [];
  340. }
  341. return $this->_normalizeAssociations($keys);
  342. }
  343. /**
  344. * Allow looping through the associations
  345. *
  346. * @return \ArrayIterator
  347. */
  348. public function getIterator()
  349. {
  350. return new ArrayIterator($this->_items);
  351. }
  352. }