forked from octobercms/library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAttachOneOrMany.php
More file actions
513 lines (441 loc) · 16 KB
/
AttachOneOrMany.php
File metadata and controls
513 lines (441 loc) · 16 KB
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
<?php namespace October\Rain\Database\Relations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Arr;
use October\Rain\Database\Attach\File as FileModel;
use Symfony\Component\HttpFoundation\File\UploadedFile;
/**
* AttachOneOrMany
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
trait AttachOneOrMany
{
use DeferOneOrMany;
/**
* @var string relationName is the "name" of the relationship
*/
protected $relationName;
/**
* @var bool public is a default value for file public or protected state
*/
protected $public;
/**
* isPublic determines if the file should be flagged "public" or not
*/
public function isPublic()
{
if (isset($this->public) && $this->public !== null) {
return $this->public;
}
return true;
}
/**
* addConstraints sets the field (relation name) constraint on the query
* @return void
*/
public function addConstraints()
{
if (static::$constraints) {
$this->query->where($this->morphType, $this->morphClass);
$this->query->where($this->foreignKey, '=', $this->getParentKey());
$this->query->where('field', $this->relationName);
$this->query->whereNotNull($this->foreignKey);
}
}
/**
* getRelationExistenceQuery adds the constraints for a relationship count query
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationExistenceQuery(Builder $query, Builder $parentQuery, $columns = ['*'])
{
if ($parentQuery->getQuery()->from === $query->getQuery()->from) {
$query = $this->getRelationExistenceQueryForSelfJoin($query, $parentQuery, $columns);
}
else {
$query = $query->select($columns)->whereColumn($this->getExistenceCompareKey(), '=', $this->getQualifiedParentKeyName());
}
$query = $query->where($this->morphType, $this->morphClass);
return $query->where('field', $this->relationName);
}
/**
* getRelationExistenceQueryForSelfRelation adds the constraints for a relationship query on the same table
* @param \Illuminate\Database\Eloquent\Builder $query
* @param \Illuminate\Database\Eloquent\Builder $parentQuery
* @param array|mixed $columns
* @return \Illuminate\Database\Eloquent\Builder
*/
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
{
$query->select($columns)->from(
$query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash()
);
$query->getModel()->setTable($hash);
return $query->whereColumn($hash.'.'.$this->getForeignKeyName(), '=', $this->getQualifiedParentKeyName());
}
/**
* addEagerConstraints sets the field constraint for an eager load of the relation
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
parent::addEagerConstraints($models);
$this->query->where('field', $this->relationName);
}
/**
* addCommonEagerConstraints adds constraints without the field constraint, used to
* eager load multiple relations of a common type.
* @see \October\Rain\Database\Concerns\HasEagerLoadAttachRelation
* @param array $models
* @return void
*/
public function addCommonEagerConstraints(array $models)
{
parent::addEagerConstraints($models);
}
/**
* save the supplied related model
*/
public function save(Model $model, $sessionKey = null)
{
if (!array_key_exists('is_public', $model->attributes)) {
$model->setAttribute('is_public', $this->isPublic());
}
$model->setAttribute('field', $this->relationName);
if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
return parent::save($model);
}
$this->add($model, $sessionKey);
return $model->save() ? $model : false;
}
/**
* saveQuietly saves the supplied related model without raising any events.
*/
public function saveQuietly(Model $model, $sessionKey = null)
{
return Model::withoutEvents(function () use ($model, $sessionKey) {
return $this->save($model, $sessionKey);
});
}
/**
* saveMany saves multiple models with deferred binding support.
*/
public function saveMany($models, $sessionKey = null)
{
foreach ($models as $model) {
$this->save($model, $sessionKey);
}
return $models;
}
/**
* saveManyQuietly saves multiple models without raising any events.
*/
public function saveManyQuietly($models, $sessionKey = null)
{
return Model::withoutEvents(function () use ($models, $sessionKey) {
return $this->saveMany($models, $sessionKey);
});
}
/**
* create a new instance of this related model
*/
public function create(array $attributes = [], $sessionKey = null)
{
if (!array_key_exists('is_public', $attributes)) {
$attributes = array_merge(['is_public' => $this->isPublic()], $attributes);
}
$attributes['field'] = $this->relationName;
if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
}
$model = parent::create($attributes);
if ($sessionKey !== null) {
$this->add($model, $sessionKey);
}
return $model;
}
/**
* createQuietly creates a new instance without raising any events.
*/
public function createQuietly(array $attributes = [], $sessionKey = null)
{
return Model::withoutEvents(function () use ($attributes, $sessionKey) {
return $this->create($attributes, $sessionKey);
});
}
/**
* createMany creates multiple instances of related models.
*/
public function createMany(iterable $records, $sessionKey = null)
{
$instances = [];
foreach ($records as $record) {
$instances[] = $this->create($record, $sessionKey);
}
return $instances;
}
/**
* createManyQuietly creates multiple instances without raising any events.
*/
public function createManyQuietly(iterable $records, $sessionKey = null)
{
return Model::withoutEvents(function () use ($records, $sessionKey) {
return $this->createMany($records, $sessionKey);
});
}
/**
* createFromFile
*/
public function createFromFile(string $filePath, array $attributes = [], $sessionKey = null)
{
if (!array_key_exists('is_public', $attributes)) {
$attributes = array_merge(['is_public' => $this->isPublic()], $attributes);
}
$attributes['field'] = $this->relationName;
if ($sessionKey === null) {
$this->ensureAttachOneIsSingular();
}
$model = parent::make($attributes);
$model->fromFile($filePath);
$model->save();
if ($sessionKey !== null) {
$this->add($model, $sessionKey);
}
return $model;
}
/**
* add a model to this relationship type
*/
public function add(Model $model, $sessionKey = null)
{
if (!array_key_exists('is_public', $model->attributes)) {
$model->is_public = $this->isPublic();
}
if ($sessionKey === null) {
/**
* @event model.relation.beforeAdd
* Called before adding a relation to the model (for AttachOneOrMany, HasOneOrMany & MorphOneOrMany relations)
*
* Example usage:
*
* $model->bindEvent('model.relation.beforeAdd', function (string $relationName, \October\Rain\Database\Model $relatedModel) use (\October\Rain\Database\Model $model) {
* if ($relationName === 'some_relation') {
* return false;
* }
* });
*
*/
if ($this->parent->fireEvent('model.relation.beforeAdd', [$this->relationName, $model], true) === false) {
return;
}
$this->ensureAttachOneIsSingular();
// Associate the model
if ($this->parent->exists) {
$model->setAttribute($this->getForeignKeyName(), $this->getParentKey());
$model->setAttribute($this->getMorphType(), $this->morphClass);
$model->setAttribute('field', $this->relationName);
$model->save();
}
else {
$this->parent->bindEventOnce('model.afterSave', function () use ($model) {
$model->setAttribute($this->getForeignKeyName(), $this->getParentKey());
$model->setAttribute($this->getMorphType(), $this->morphClass);
$model->setAttribute('field', $this->relationName);
$model->save();
});
}
// Use the opportunity to set the relation in memory
if ($this instanceof AttachOne) {
$this->parent->setRelation($this->relationName, $model);
}
else {
$this->parent->unsetRelation($this->relationName);
}
/**
* @event model.relation.add
* Called after adding a relation to the model (for AttachOneOrMany, HasOneOrMany & MorphOneOrMany relations)
*
* Example usage:
*
* $model->bindEvent('model.relation.add', function (string $relationName, \October\Rain\Database\Model $relatedModel) use (\October\Rain\Database\Model $model) {
* $relatedClass = get_class($relatedModel);
* $modelClass = get_class($model);
* traceLog("{$relatedClass} was added as {$relationName} to {$modelClass}.");
* });
*
*/
$this->parent->fireEvent('model.relation.add', [$this->relationName, $model]);
}
else {
$this->ensureAttachOneIsSingular($sessionKey);
$this->parent->bindDeferred($this->relationName, $model, $sessionKey);
}
}
/**
* addMany attaches an array of models to the parent instance with deferred binding support
* @param array $models
*/
public function addMany($models, $sessionKey = null)
{
foreach ($models as $model) {
$this->add($model, $sessionKey);
}
}
/**
* remove a model from this relationship type
*/
public function remove(Model $model, $sessionKey = null)
{
if ($sessionKey === null) {
/**
* @event model.relation.beforeRemove
* Called before removing a relation to the model (for AttachOneOrMany, HasOneOrMany & MorphOneOrMany relations)
*
* Example usage:
*
* $model->bindEvent('model.relation.beforeRemove', function (string $relationName, \October\Rain\Database\Model $relatedModel) use (\October\Rain\Database\Model $model) {
* if ($relationName === 'perm_relation') {
* return false;
* }
* });
*
*/
if ($this->parent->fireEvent('model.relation.beforeRemove', [$this->relationName, $model], true) === false) {
return;
}
if (!$this->isModelRemovable($model)) {
return;
}
$options = $this->parent->getRelationDefinition($this->relationName);
if (Arr::get($options, 'delete', false)) {
$model->delete();
}
else {
// Make this model an orphan ;~(
$model->setAttribute($this->getForeignKeyName(), null);
$model->setAttribute($this->getMorphType(), null);
$model->setAttribute('field', null);
$model->save();
}
// Use the opportunity to set the relation in memory
if ($this instanceof AttachOne) {
$this->parent->setRelation($this->relationName, null);
}
else {
$this->parent->unsetRelation($this->relationName);
}
/**
* @event model.relation.remove
* Called after removing a relation to the model (for AttachOneOrMany, HasOneOrMany & MorphOneOrMany relations)
*
* Example usage:
*
* $model->bindEvent('model.relation.remove', function (string $relationName, \October\Rain\Database\Model $relatedModel) use (\October\Rain\Database\Model $model) {
* $relatedClass = get_class($relatedModel);
* $modelClass = get_class($model);
* traceLog("{$relatedClass} was removed from {$modelClass}.");
* });
*
*/
$this->parent->fireEvent('model.relation.remove', [$this->relationName, $model]);
}
else {
$this->parent->unbindDeferred($this->relationName, $model, $sessionKey);
}
}
/**
* isModelRemovable returns true if an existing model is already associated
*/
protected function isModelRemovable($model): bool
{
return
((string) $model->getAttribute($this->getForeignKeyName()) === (string) $this->getParentKey()) &&
$model->getAttribute($this->getMorphType()) === $this->morphClass &&
$model->getAttribute('field') === $this->relationName;
}
/**
* ensureAttachOneIsSingular ensures AttachOne only has one attachment,
* by deleting siblings for singular relations.
*/
protected function ensureAttachOneIsSingular($sessionKey = null)
{
if (!$this instanceof AttachOne) {
return;
}
if ($sessionKey) {
foreach ($this->withDeferred($sessionKey)->get() as $record) {
$this->parent->unbindDeferred($this->relationName, $record, $sessionKey);
}
return;
}
if ($this->parent->exists) {
$this->delete();
}
}
/**
* @deprecated this method is removed in October CMS v4
*/
public function makeValidationFile($value)
{
if ($value instanceof FileModel) {
$localPath = $value->getLocalPath();
// Exception handling for UploadedFile
if (file_exists($localPath)) {
return new UploadedFile(
$localPath,
$value->file_name,
$value->content_type,
null,
true
);
}
// Fallback to string
$value = $localPath;
}
/*
* @todo `$value` might be a string, may not validate
*/
return $value;
}
/**
* ensureRelationIsEmpty ensures the relation is empty, either deleted or nulled.
*/
protected function ensureRelationIsEmpty()
{
$options = $this->parent->getRelationDefinition($this->relationName);
if (Arr::get($options, 'delete', false)) {
$this->delete();
}
else {
$this->update([$this->getForeignKeyName() => null]);
}
}
/**
* getRelatedKeyName
* @return string
*/
public function getRelatedKeyName()
{
return $this->related->getKeyName();
}
/**
* @deprecated use getForeignKeyName
*/
public function getForeignKey()
{
return $this->foreignKey;
}
/**
* @deprecated use getLocalKeyName
*/
public function getOtherKey()
{
return $this->localKey;
}
}