-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
HasMany.php
429 lines (383 loc) · 14.1 KB
/
HasMany.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
<?php
/**
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 3.0.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\ORM\Association;
use Cake\Collection\Collection;
use Cake\Datasource\EntityInterface;
use Cake\ORM\Association;
use Cake\ORM\Table;
use InvalidArgumentException;
use RuntimeException;
use Traversable;
/**
* Represents an N - 1 relationship where the target side of the relationship
* will have one or multiple records per each one in the source side.
*
* An example of a HasMany association would be Author has many Articles.
*/
class HasMany extends Association
{
use DependentDeleteTrait;
use ExternalAssociationTrait {
_options as _externalOptions;
}
/**
* The type of join to be used when adding the association to a query
*
* @var string
*/
protected $_joinType = 'INNER';
/**
* The strategy name to be used to fetch associated records.
*
* @var string
*/
protected $_strategy = self::STRATEGY_SELECT;
/**
* Valid strategies for this type of association
*
* @var array
*/
protected $_validStrategies = [self::STRATEGY_SELECT, self::STRATEGY_SUBQUERY];
/**
* Saving strategy that will only append to the links set
*
* @var string
*/
const SAVE_APPEND = 'append';
/**
* Saving strategy that will replace the links with the provided set
*
* @var string
*/
const SAVE_REPLACE = 'replace';
/**
* Saving strategy to be used by this association
*
* @var string
*/
protected $_saveStrategy = self::SAVE_APPEND;
/**
* Returns whether or not the passed table is the owning side for this
* association. This means that rows in the 'target' table would miss important
* or required information if the row in 'source' did not exist.
*
* @param \Cake\ORM\Table $side The potential Table with ownership
* @return bool
*/
public function isOwningSide(Table $side)
{
return $side === $this->source();
}
/**
* Sets the strategy that should be used for saving. If called with no
* arguments, it will return the currently configured strategy
*
* @param string|null $strategy the strategy name to be used
* @throws \InvalidArgumentException if an invalid strategy name is passed
* @return string the strategy to be used for saving
*/
public function saveStrategy($strategy = null)
{
if ($strategy === null) {
return $this->_saveStrategy;
}
if (!in_array($strategy, [self::SAVE_APPEND, self::SAVE_REPLACE])) {
$msg = sprintf('Invalid save strategy "%s"', $strategy);
throw new InvalidArgumentException($msg);
}
return $this->_saveStrategy = $strategy;
}
/**
* Takes an entity from the source table and looks if there is a field
* matching the property name for this association. The found entity will be
* saved on the target table for this association by passing supplied
* `$options`
*
* @param \Cake\Datasource\EntityInterface $entity an entity from the source table
* @param array|\ArrayObject $options options to be passed to the save method in
* the target table
* @return bool|\Cake\Datasource\EntityInterface false if $entity could not be saved, otherwise it returns
* the saved entity
* @see Table::save()
* @throws \InvalidArgumentException when the association data cannot be traversed.
*/
public function saveAssociated(EntityInterface $entity, array $options = [])
{
$targetEntities = $entity->get($this->property());
if (empty($targetEntities) && $this->_saveStrategy !== self::SAVE_REPLACE) {
return $entity;
}
if (!is_array($targetEntities) && !($targetEntities instanceof Traversable)) {
$name = $this->property();
$message = sprintf('Could not save %s, it cannot be traversed', $name);
throw new InvalidArgumentException($message);
}
$foreignKey = (array)$this->foreignKey();
$properties = array_combine(
$foreignKey,
$entity->extract((array)$this->bindingKey())
);
$target = $this->target();
$original = $targetEntities;
$options['_sourceTable'] = $this->source();
if ($this->_saveStrategy === self::SAVE_REPLACE) {
$this->_unlinkAssociated($properties, $entity, $target, $targetEntities);
}
foreach ($targetEntities as $k => $targetEntity) {
if (!($targetEntity instanceof EntityInterface)) {
break;
}
if (!empty($options['atomic'])) {
$targetEntity = clone $targetEntity;
}
if ($properties !== $targetEntity->extract($foreignKey)) {
$targetEntity->set($properties, ['guard' => false]);
}
if ($target->save($targetEntity, $options)) {
$targetEntities[$k] = $targetEntity;
continue;
}
if (!empty($options['atomic'])) {
$original[$k]->errors($targetEntity->errors());
$entity->set($this->property(), $original);
return false;
}
}
$entity->set($this->property(), $targetEntities);
return $entity;
}
/**
* Associates the source entity to each of the target entities provided.
* When using this method, all entities in `$targetEntities` will be appended to
* the source entity's property corresponding to this association object.
*
* This method does not check link uniqueness.
*
* ### Example:
*
* ```
* $user = $users->get(1);
* $allArticles = $articles->find('all')->execute();
* $users->Articles->link($user, $allArticles);
* ```
*
* `$user->get('articles')` will contain all articles in `$allArticles` after linking
*
* @param \Cake\Datasource\EntityInterface $sourceEntity the row belonging to the `source` side
* of this association
* @param array $targetEntities list of entities belonging to the `target` side
* of this association
* @param array $options list of options to be passed to the save method
* @return bool true on success, false otherwise
*/
public function link(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
{
$saveStrategy = $this->saveStrategy();
$this->saveStrategy(self::SAVE_APPEND);
$source = $this->source();
$property = $this->property();
$currentEntities = (new Collection((array)$sourceEntity->get($property)))->append($targetEntities);
$sourceEntity->set($property, $currentEntities->toList());
$savedEntity = $this->saveAssociated($sourceEntity);
$ok = ($savedEntity instanceof EntityInterface);
$this->saveStrategy($saveStrategy);
if ($ok) {
$sourceEntity->set($property, $savedEntity->get($property));
$sourceEntity->clean($property);
}
return $ok;
}
/**
* Removes all links between the passed source entity and each of the provided
* target entities. This method assumes that all passed objects are already persisted
* in the database and that each of them contain a primary key value.
*
* By default this method will also unset each of the entity objects stored inside
* the source entity.
*
* ### Example:
*
* ```
* $user = $users->get(1);
* $user->articles = [$article1, $article2, $article3, $article4];
* $users->save($user, ['Associated' => ['Articles']]);
* $allArticles = [$article1, $article2, $article3];
* $users->Articles->unlink($user, $allArticles);
* ```
*
* `$article->get('articles')` will contain only `[$article4]` after deleting in the database
*
* @param \Cake\Datasource\EntityInterface $sourceEntity an entity persisted in the source table for
* this association
* @param array $targetEntities list of entities persisted in the target table for
* this association
* @param bool $cleanProperty whether or not to remove all the objects in $targetEntities
* that are stored in $sourceEntity
* @throws \InvalidArgumentException if non persisted entities are passed or if
* any of them is lacking a primary key value
* @return void
*/
public function unlink(EntityInterface $sourceEntity, array $targetEntities, $cleanProperty = true)
{
$foreignKey = (array)$this->foreignKey();
$target = $this->target();
$targetPrimaryKey = array_merge((array)$target->primaryKey(), (array)$foreignKey);
$property = $this->property();
$conditions = [
'OR' => (new Collection($targetEntities) )
->map(function ($entity) use ($targetPrimaryKey) {
return $entity->extract($targetPrimaryKey);
})
->toList()
];
$this->_unlink($foreignKey, $target, $conditions);
if ($cleanProperty) {
$sourceEntity->set(
$property,
(new Collection($sourceEntity->get($property)))
->reject(
function ($assoc) use ($targetEntities) {
return in_array($assoc, $targetEntities);
}
)
->toList()
);
}
}
/**
* Deletes/sets null the related objects according to the dependency between source and targets and foreign key nullability
* Skips deleting records present in $remainingEntities
*
* @param array $properties array of foreignKey properties
* @param EntityInterface $entity the entity which should have its associated entities unassigned
* @param Table $target The associated table
* @param array $remainingEntities Entities that should not be deleted
* @return void
*/
protected function _unlinkAssociated(array $properties, EntityInterface $entity, Table $target, array $remainingEntities = [])
{
$primaryKey = (array)$target->primaryKey();
$exclusions = new Collection($remainingEntities);
$exclusions = $exclusions->map(
function ($ent) use ($primaryKey) {
return $ent->extract($primaryKey);
}
)
->filter(
function ($v) {
return !in_array(null, array_values($v), true);
}
)
->toArray();
$conditions = $properties;
if (count($exclusions) > 0) {
$conditions = [
'NOT' => [
'OR' => $exclusions
],
$properties
];
}
$this->_unlink(array_keys($properties), $target, $conditions);
}
/**
* Deletes/sets null the related objects matching $conditions.
* The action which is taken depends on the dependency between source and targets and also on foreign key nullability
*
* @param array $foreignKey array of foreign key properties
* @param Table $target The associated table
* @param array $conditions The conditions that specifies what are the objects to be unlinked
* @return void
*/
protected function _unlink(array $foreignKey, Table $target, array $conditions = [])
{
$mustBeDependent = (!$this->_foreignKeyAcceptsNull($target, $foreignKey) || $this->dependent());
if ($mustBeDependent) {
if ($this->_cascadeCallbacks) {
$query = $this->find('all')->where($conditions);
foreach ($query as $assoc) {
$target->delete($assoc);
}
} else {
$target->deleteAll($conditions);
}
} else {
$updateFields = array_fill_keys($foreignKey, null);
$target->updateAll($updateFields, $conditions);
}
}
/**
* Checks the nullable flag of the foreign key
*
* @param Table $table the table containing the foreign key
* @param array $properties the list of fields that compose the foreign key
* @return bool
*/
protected function _foreignKeyAcceptsNull(Table $table, array $properties)
{
return !in_array(
false,
array_map(
function ($prop) use ($table) {
return $table->schema()->isNullable($prop);
},
$properties
)
);
}
/**
* {@inheritDoc}
*/
protected function _linkField($options)
{
$links = [];
$name = $this->alias();
if ($options['foreignKey'] === false) {
$msg = 'Cannot have foreignKey = false for hasMany associations. ' .
'You must provide a foreignKey column.';
throw new RuntimeException($msg);
}
foreach ((array)$options['foreignKey'] as $key) {
$links[] = sprintf('%s.%s', $name, $key);
}
if (count($links) === 1) {
return $links[0];
}
return $links;
}
/**
* Get the relationship type.
*
* @return string
*/
public function type()
{
return self::ONE_TO_MANY;
}
/**
* Parse extra options passed in the constructor.
*
* @param array $opts original list of options passed in constructor
* @return void
*/
protected function _options(array $opts)
{
$this->_externalOptions($opts);
if (!empty($opts['saveStrategy'])) {
$this->saveStrategy($opts['saveStrategy']);
}
}
}