1: <?php
2: /**
3: *
4: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
5: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
6: *
7: * Licensed under The MIT License
8: * For full copyright and license information, please see the LICENSE.txt
9: * Redistributions of files must retain the above copyright notice.
10: *
11: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
12: * @link https://cakephp.org CakePHP(tm) Project
13: * @since 3.0.0
14: * @license https://opensource.org/licenses/mit-license.php MIT License
15: */
16: namespace Cake\ORM\Association;
17:
18: use Cake\Collection\Collection;
19: use Cake\Database\Expression\FieldInterface;
20: use Cake\Database\Expression\QueryExpression;
21: use Cake\Datasource\EntityInterface;
22: use Cake\Datasource\QueryInterface;
23: use Cake\ORM\Association;
24: use Cake\ORM\Association\DependentDeleteHelper;
25: use Cake\ORM\Association\Loader\SelectLoader;
26: use Cake\ORM\Table;
27: use InvalidArgumentException;
28: use Traversable;
29:
30: /**
31: * Represents an N - 1 relationship where the target side of the relationship
32: * will have one or multiple records per each one in the source side.
33: *
34: * An example of a HasMany association would be Author has many Articles.
35: */
36: class HasMany extends Association
37: {
38:
39: /**
40: * Order in which target records should be returned
41: *
42: * @var mixed
43: */
44: protected $_sort;
45:
46: /**
47: * The type of join to be used when adding the association to a query
48: *
49: * @var string
50: */
51: protected $_joinType = QueryInterface::JOIN_TYPE_INNER;
52:
53: /**
54: * The strategy name to be used to fetch associated records.
55: *
56: * @var string
57: */
58: protected $_strategy = self::STRATEGY_SELECT;
59:
60: /**
61: * Valid strategies for this type of association
62: *
63: * @var array
64: */
65: protected $_validStrategies = [
66: self::STRATEGY_SELECT,
67: self::STRATEGY_SUBQUERY
68: ];
69:
70: /**
71: * Saving strategy that will only append to the links set
72: *
73: * @var string
74: */
75: const SAVE_APPEND = 'append';
76:
77: /**
78: * Saving strategy that will replace the links with the provided set
79: *
80: * @var string
81: */
82: const SAVE_REPLACE = 'replace';
83:
84: /**
85: * Saving strategy to be used by this association
86: *
87: * @var string
88: */
89: protected $_saveStrategy = self::SAVE_APPEND;
90:
91: /**
92: * Returns whether or not the passed table is the owning side for this
93: * association. This means that rows in the 'target' table would miss important
94: * or required information if the row in 'source' did not exist.
95: *
96: * @param \Cake\ORM\Table $side The potential Table with ownership
97: * @return bool
98: */
99: public function isOwningSide(Table $side)
100: {
101: return $side === $this->getSource();
102: }
103:
104: /**
105: * Sets the strategy that should be used for saving.
106: *
107: * @param string $strategy the strategy name to be used
108: * @throws \InvalidArgumentException if an invalid strategy name is passed
109: * @return $this
110: */
111: public function setSaveStrategy($strategy)
112: {
113: if (!in_array($strategy, [self::SAVE_APPEND, self::SAVE_REPLACE])) {
114: $msg = sprintf('Invalid save strategy "%s"', $strategy);
115: throw new InvalidArgumentException($msg);
116: }
117:
118: $this->_saveStrategy = $strategy;
119:
120: return $this;
121: }
122:
123: /**
124: * Gets the strategy that should be used for saving.
125: *
126: * @return string the strategy to be used for saving
127: */
128: public function getSaveStrategy()
129: {
130: return $this->_saveStrategy;
131: }
132:
133: /**
134: * Sets the strategy that should be used for saving. If called with no
135: * arguments, it will return the currently configured strategy
136: *
137: * @deprecated 3.4.0 Use setSaveStrategy()/getSaveStrategy() instead.
138: * @param string|null $strategy the strategy name to be used
139: * @throws \InvalidArgumentException if an invalid strategy name is passed
140: * @return string the strategy to be used for saving
141: */
142: public function saveStrategy($strategy = null)
143: {
144: deprecationWarning(
145: 'HasMany::saveStrategy() is deprecated. ' .
146: 'Use setSaveStrategy()/getSaveStrategy() instead.'
147: );
148: if ($strategy !== null) {
149: $this->setSaveStrategy($strategy);
150: }
151:
152: return $this->getSaveStrategy();
153: }
154:
155: /**
156: * Takes an entity from the source table and looks if there is a field
157: * matching the property name for this association. The found entity will be
158: * saved on the target table for this association by passing supplied
159: * `$options`
160: *
161: * @param \Cake\Datasource\EntityInterface $entity an entity from the source table
162: * @param array $options options to be passed to the save method in the target table
163: * @return bool|\Cake\Datasource\EntityInterface false if $entity could not be saved, otherwise it returns
164: * the saved entity
165: * @see \Cake\ORM\Table::save()
166: * @throws \InvalidArgumentException when the association data cannot be traversed.
167: */
168: public function saveAssociated(EntityInterface $entity, array $options = [])
169: {
170: $targetEntities = $entity->get($this->getProperty());
171:
172: $isEmpty = in_array($targetEntities, [null, [], '', false], true);
173: if ($isEmpty) {
174: if ($entity->isNew() ||
175: $this->getSaveStrategy() !== self::SAVE_REPLACE
176: ) {
177: return $entity;
178: }
179:
180: $targetEntities = [];
181: }
182:
183: if (!is_array($targetEntities) &&
184: !($targetEntities instanceof Traversable)
185: ) {
186: $name = $this->getProperty();
187: $message = sprintf('Could not save %s, it cannot be traversed', $name);
188: throw new InvalidArgumentException($message);
189: }
190:
191: $foreignKeyReference = array_combine(
192: (array)$this->getForeignKey(),
193: $entity->extract((array)$this->getBindingKey())
194: );
195:
196: $options['_sourceTable'] = $this->getSource();
197:
198: if ($this->_saveStrategy === self::SAVE_REPLACE &&
199: !$this->_unlinkAssociated($foreignKeyReference, $entity, $this->getTarget(), $targetEntities, $options)
200: ) {
201: return false;
202: }
203:
204: if (!$this->_saveTarget($foreignKeyReference, $entity, $targetEntities, $options)) {
205: return false;
206: }
207:
208: return $entity;
209: }
210:
211: /**
212: * Persists each of the entities into the target table and creates links between
213: * the parent entity and each one of the saved target entities.
214: *
215: * @param array $foreignKeyReference The foreign key reference defining the link between the
216: * target entity, and the parent entity.
217: * @param \Cake\Datasource\EntityInterface $parentEntity The source entity containing the target
218: * entities to be saved.
219: * @param array|\Traversable $entities list of entities to persist in target table and to
220: * link to the parent entity
221: * @param array $options list of options accepted by `Table::save()`.
222: * @return bool `true` on success, `false` otherwise.
223: */
224: protected function _saveTarget(array $foreignKeyReference, EntityInterface $parentEntity, $entities, array $options)
225: {
226: $foreignKey = array_keys($foreignKeyReference);
227: $table = $this->getTarget();
228: $original = $entities;
229:
230: foreach ($entities as $k => $entity) {
231: if (!($entity instanceof EntityInterface)) {
232: break;
233: }
234:
235: if (!empty($options['atomic'])) {
236: $entity = clone $entity;
237: }
238:
239: if ($foreignKeyReference !== $entity->extract($foreignKey)) {
240: $entity->set($foreignKeyReference, ['guard' => false]);
241: }
242:
243: if ($table->save($entity, $options)) {
244: $entities[$k] = $entity;
245: continue;
246: }
247:
248: if (!empty($options['atomic'])) {
249: $original[$k]->setErrors($entity->getErrors());
250: $entity->set($this->getProperty(), $original);
251:
252: return false;
253: }
254: }
255:
256: $parentEntity->set($this->getProperty(), $entities);
257:
258: return true;
259: }
260:
261: /**
262: * Associates the source entity to each of the target entities provided.
263: * When using this method, all entities in `$targetEntities` will be appended to
264: * the source entity's property corresponding to this association object.
265: *
266: * This method does not check link uniqueness.
267: * Changes are persisted in the database and also in the source entity.
268: *
269: * ### Example:
270: *
271: * ```
272: * $user = $users->get(1);
273: * $allArticles = $articles->find('all')->toArray();
274: * $users->Articles->link($user, $allArticles);
275: * ```
276: *
277: * `$user->get('articles')` will contain all articles in `$allArticles` after linking
278: *
279: * @param \Cake\Datasource\EntityInterface $sourceEntity the row belonging to the `source` side
280: * of this association
281: * @param array $targetEntities list of entities belonging to the `target` side
282: * of this association
283: * @param array $options list of options to be passed to the internal `save` call
284: * @return bool true on success, false otherwise
285: */
286: public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
287: {
288: $saveStrategy = $this->getSaveStrategy();
289: $this->setSaveStrategy(self::SAVE_APPEND);
290: $property = $this->getProperty();
291:
292: $currentEntities = array_unique(
293: array_merge(
294: (array)$sourceEntity->get($property),
295: $targetEntities
296: )
297: );
298:
299: $sourceEntity->set($property, $currentEntities);
300:
301: $savedEntity = $this->getConnection()->transactional(function () use ($sourceEntity, $options) {
302: return $this->saveAssociated($sourceEntity, $options);
303: });
304:
305: $ok = ($savedEntity instanceof EntityInterface);
306:
307: $this->setSaveStrategy($saveStrategy);
308:
309: if ($ok) {
310: $sourceEntity->set($property, $savedEntity->get($property));
311: $sourceEntity->setDirty($property, false);
312: }
313:
314: return $ok;
315: }
316:
317: /**
318: * Removes all links between the passed source entity and each of the provided
319: * target entities. This method assumes that all passed objects are already persisted
320: * in the database and that each of them contain a primary key value.
321: *
322: * ### Options
323: *
324: * Additionally to the default options accepted by `Table::delete()`, the following
325: * keys are supported:
326: *
327: * - cleanProperty: Whether or not to remove all the objects in `$targetEntities` that
328: * are stored in `$sourceEntity` (default: true)
329: *
330: * By default this method will unset each of the entity objects stored inside the
331: * source entity.
332: *
333: * Changes are persisted in the database and also in the source entity.
334: *
335: * ### Example:
336: *
337: * ```
338: * $user = $users->get(1);
339: * $user->articles = [$article1, $article2, $article3, $article4];
340: * $users->save($user, ['Associated' => ['Articles']]);
341: * $allArticles = [$article1, $article2, $article3];
342: * $users->Articles->unlink($user, $allArticles);
343: * ```
344: *
345: * `$article->get('articles')` will contain only `[$article4]` after deleting in the database
346: *
347: * @param \Cake\Datasource\EntityInterface $sourceEntity an entity persisted in the source table for
348: * this association
349: * @param array $targetEntities list of entities persisted in the target table for
350: * this association
351: * @param array $options list of options to be passed to the internal `delete` call
352: * @throws \InvalidArgumentException if non persisted entities are passed or if
353: * any of them is lacking a primary key value
354: * @return void
355: */
356: public function unlink(EntityInterface $sourceEntity, array $targetEntities, $options = [])
357: {
358: if (is_bool($options)) {
359: $options = [
360: 'cleanProperty' => $options
361: ];
362: } else {
363: $options += ['cleanProperty' => true];
364: }
365: if (count($targetEntities) === 0) {
366: return;
367: }
368:
369: $foreignKey = (array)$this->getForeignKey();
370: $target = $this->getTarget();
371: $targetPrimaryKey = array_merge((array)$target->getPrimaryKey(), $foreignKey);
372: $property = $this->getProperty();
373:
374: $conditions = [
375: 'OR' => (new Collection($targetEntities))
376: ->map(function ($entity) use ($targetPrimaryKey) {
377: return $entity->extract($targetPrimaryKey);
378: })
379: ->toList()
380: ];
381:
382: $this->_unlink($foreignKey, $target, $conditions, $options);
383:
384: $result = $sourceEntity->get($property);
385: if ($options['cleanProperty'] && $result !== null) {
386: $sourceEntity->set(
387: $property,
388: (new Collection($sourceEntity->get($property)))
389: ->reject(
390: function ($assoc) use ($targetEntities) {
391: return in_array($assoc, $targetEntities);
392: }
393: )
394: ->toList()
395: );
396: }
397:
398: $sourceEntity->setDirty($property, false);
399: }
400:
401: /**
402: * Replaces existing association links between the source entity and the target
403: * with the ones passed. This method does a smart cleanup, links that are already
404: * persisted and present in `$targetEntities` will not be deleted, new links will
405: * be created for the passed target entities that are not already in the database
406: * and the rest will be removed.
407: *
408: * For example, if an author has many articles, such as 'article1','article 2' and 'article 3' and you pass
409: * to this method an array containing the entities for articles 'article 1' and 'article 4',
410: * only the link for 'article 1' will be kept in database, the links for 'article 2' and 'article 3' will be
411: * deleted and the link for 'article 4' will be created.
412: *
413: * Existing links are not deleted and created again, they are either left untouched
414: * or updated.
415: *
416: * This method does not check link uniqueness.
417: *
418: * On success, the passed `$sourceEntity` will contain `$targetEntities` as value
419: * in the corresponding property for this association.
420: *
421: * Additional options for new links to be saved can be passed in the third argument,
422: * check `Table::save()` for information on the accepted options.
423: *
424: * ### Example:
425: *
426: * ```
427: * $author->articles = [$article1, $article2, $article3, $article4];
428: * $authors->save($author);
429: * $articles = [$article1, $article3];
430: * $authors->getAssociation('articles')->replace($author, $articles);
431: * ```
432: *
433: * `$author->get('articles')` will contain only `[$article1, $article3]` at the end
434: *
435: * @param \Cake\Datasource\EntityInterface $sourceEntity an entity persisted in the source table for
436: * this association
437: * @param array $targetEntities list of entities from the target table to be linked
438: * @param array $options list of options to be passed to the internal `save`/`delete` calls
439: * when persisting/updating new links, or deleting existing ones
440: * @throws \InvalidArgumentException if non persisted entities are passed or if
441: * any of them is lacking a primary key value
442: * @return bool success
443: */
444: public function replace(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
445: {
446: $property = $this->getProperty();
447: $sourceEntity->set($property, $targetEntities);
448: $saveStrategy = $this->getSaveStrategy();
449: $this->setSaveStrategy(self::SAVE_REPLACE);
450: $result = $this->saveAssociated($sourceEntity, $options);
451: $ok = ($result instanceof EntityInterface);
452:
453: if ($ok) {
454: $sourceEntity = $result;
455: }
456: $this->setSaveStrategy($saveStrategy);
457:
458: return $ok;
459: }
460:
461: /**
462: * Deletes/sets null the related objects according to the dependency between source and targets and foreign key nullability
463: * Skips deleting records present in $remainingEntities
464: *
465: * @param array $foreignKeyReference The foreign key reference defining the link between the
466: * target entity, and the parent entity.
467: * @param \Cake\Datasource\EntityInterface $entity the entity which should have its associated entities unassigned
468: * @param \Cake\ORM\Table $target The associated table
469: * @param array $remainingEntities Entities that should not be deleted
470: * @param array $options list of options accepted by `Table::delete()`
471: * @return bool success
472: */
473: protected function _unlinkAssociated(array $foreignKeyReference, EntityInterface $entity, Table $target, array $remainingEntities = [], array $options = [])
474: {
475: $primaryKey = (array)$target->getPrimaryKey();
476: $exclusions = new Collection($remainingEntities);
477: $exclusions = $exclusions->map(
478: function ($ent) use ($primaryKey) {
479: return $ent->extract($primaryKey);
480: }
481: )
482: ->filter(
483: function ($v) {
484: return !in_array(null, $v, true);
485: }
486: )
487: ->toList();
488:
489: $conditions = $foreignKeyReference;
490:
491: if (count($exclusions) > 0) {
492: $conditions = [
493: 'NOT' => [
494: 'OR' => $exclusions
495: ],
496: $foreignKeyReference
497: ];
498: }
499:
500: return $this->_unlink(array_keys($foreignKeyReference), $target, $conditions, $options);
501: }
502:
503: /**
504: * Deletes/sets null the related objects matching $conditions.
505: * The action which is taken depends on the dependency between source and targets and also on foreign key nullability
506: *
507: * @param array $foreignKey array of foreign key properties
508: * @param \Cake\ORM\Table $target The associated table
509: * @param array $conditions The conditions that specifies what are the objects to be unlinked
510: * @param array $options list of options accepted by `Table::delete()`
511: * @return bool success
512: */
513: protected function _unlink(array $foreignKey, Table $target, array $conditions = [], array $options = [])
514: {
515: $mustBeDependent = (!$this->_foreignKeyAcceptsNull($target, $foreignKey) || $this->getDependent());
516:
517: if ($mustBeDependent) {
518: if ($this->_cascadeCallbacks) {
519: $conditions = new QueryExpression($conditions);
520: $conditions->traverse(function ($entry) use ($target) {
521: if ($entry instanceof FieldInterface) {
522: $entry->setField($target->aliasField($entry->getField()));
523: }
524: });
525: $query = $this->find('all')->where($conditions);
526: $ok = true;
527: foreach ($query as $assoc) {
528: $ok = $ok && $target->delete($assoc, $options);
529: }
530:
531: return $ok;
532: }
533:
534: $conditions = array_merge($conditions, $this->getConditions());
535: $target->deleteAll($conditions);
536:
537: return true;
538: }
539:
540: $updateFields = array_fill_keys($foreignKey, null);
541: $conditions = array_merge($conditions, $this->getConditions());
542: $target->updateAll($updateFields, $conditions);
543:
544: return true;
545: }
546:
547: /**
548: * Checks the nullable flag of the foreign key
549: *
550: * @param \Cake\ORM\Table $table the table containing the foreign key
551: * @param array $properties the list of fields that compose the foreign key
552: * @return bool
553: */
554: protected function _foreignKeyAcceptsNull(Table $table, array $properties)
555: {
556: return !in_array(
557: false,
558: array_map(
559: function ($prop) use ($table) {
560: return $table->getSchema()->isNullable($prop);
561: },
562: $properties
563: )
564: );
565: }
566:
567: /**
568: * Get the relationship type.
569: *
570: * @return string
571: */
572: public function type()
573: {
574: return self::ONE_TO_MANY;
575: }
576:
577: /**
578: * Whether this association can be expressed directly in a query join
579: *
580: * @param array $options custom options key that could alter the return value
581: * @return bool if the 'matching' key in $option is true then this function
582: * will return true, false otherwise
583: */
584: public function canBeJoined(array $options = [])
585: {
586: return !empty($options['matching']);
587: }
588:
589: /**
590: * Gets the name of the field representing the foreign key to the source table.
591: *
592: * @return string
593: */
594: public function getForeignKey()
595: {
596: if ($this->_foreignKey === null) {
597: $this->_foreignKey = $this->_modelKey($this->getSource()->getTable());
598: }
599:
600: return $this->_foreignKey;
601: }
602:
603: /**
604: * Sets the sort order in which target records should be returned.
605: *
606: * @param mixed $sort A find() compatible order clause
607: * @return $this
608: */
609: public function setSort($sort)
610: {
611: $this->_sort = $sort;
612:
613: return $this;
614: }
615:
616: /**
617: * Gets the sort order in which target records should be returned.
618: *
619: * @return mixed
620: */
621: public function getSort()
622: {
623: return $this->_sort;
624: }
625:
626: /**
627: * Sets the sort order in which target records should be returned.
628: * If no arguments are passed the currently configured value is returned
629: *
630: * @deprecated 3.4.0 Use setSort()/getSort() instead.
631: * @param mixed $sort A find() compatible order clause
632: * @return mixed
633: */
634: public function sort($sort = null)
635: {
636: deprecationWarning(
637: 'HasMany::sort() is deprecated. ' .
638: 'Use setSort()/getSort() instead.'
639: );
640: if ($sort !== null) {
641: $this->setSort($sort);
642: }
643:
644: return $this->getSort();
645: }
646:
647: /**
648: * {@inheritDoc}
649: */
650: public function defaultRowValue($row, $joined)
651: {
652: $sourceAlias = $this->getSource()->getAlias();
653: if (isset($row[$sourceAlias])) {
654: $row[$sourceAlias][$this->getProperty()] = $joined ? null : [];
655: }
656:
657: return $row;
658: }
659:
660: /**
661: * Parse extra options passed in the constructor.
662: *
663: * @param array $opts original list of options passed in constructor
664: * @return void
665: */
666: protected function _options(array $opts)
667: {
668: if (!empty($opts['saveStrategy'])) {
669: $this->setSaveStrategy($opts['saveStrategy']);
670: }
671: if (isset($opts['sort'])) {
672: $this->setSort($opts['sort']);
673: }
674: }
675:
676: /**
677: * {@inheritDoc}
678: *
679: * @return \Closure
680: */
681: public function eagerLoader(array $options)
682: {
683: $loader = new SelectLoader([
684: 'alias' => $this->getAlias(),
685: 'sourceAlias' => $this->getSource()->getAlias(),
686: 'targetAlias' => $this->getTarget()->getAlias(),
687: 'foreignKey' => $this->getForeignKey(),
688: 'bindingKey' => $this->getBindingKey(),
689: 'strategy' => $this->getStrategy(),
690: 'associationType' => $this->type(),
691: 'sort' => $this->getSort(),
692: 'finder' => [$this, 'find']
693: ]);
694:
695: return $loader->buildEagerLoader($options);
696: }
697:
698: /**
699: * {@inheritDoc}
700: */
701: public function cascadeDelete(EntityInterface $entity, array $options = [])
702: {
703: $helper = new DependentDeleteHelper();
704:
705: return $helper->cascadeDelete($this, $entity, $options);
706: }
707: }
708: