forked from octobercms/library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultisite.php
More file actions
497 lines (426 loc) · 14.5 KB
/
Multisite.php
File metadata and controls
497 lines (426 loc) · 14.5 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
<?php namespace October\Rain\Database\Traits;
use Illuminate\Support\Arr;
use Site;
use October\Rain\Database\Scopes\MultisiteScope;
use Exception;
/**
* Multisite trait allows for site-based models, the database
* table should contain site_id and site_root_id keys
*
* @package october\database
* @author Alexey Bobkov, Samuel Georges
*/
trait Multisite
{
/**
* @var array propagatable list of attributes to propagate to other sites.
*
* protected $propagatable = [];
*/
/**
* @var bool|array propagatableSync will enforce model structures between all sites.
* When set to `false` will disable sync, set `true` will sync between the site group.
* The sync option allow sync to `all` sites, sites in the `group`, and sites the `locale`.
*
* Set to an array of options for more granular controls:
*
* - **sync** - logic to sync specific sites, available options: `all`, `group`, `locale`
* - **structure** - enable the sync of tree/sortable structures, default: `true`
* - **delete** - delete all linked records when any record is deleted, default: `true`
*
* protected $propagatableSync = false;
*/
/**
* bootMultisite trait for a model.
*/
public static function bootMultisite()
{
static::addGlobalScope(new MultisiteScope);
}
/**
* initializeMultisite
*/
public function initializeMultisite()
{
if (!is_array($this->propagatable)) {
throw new Exception(sprintf(
'The $propagatable property in %s must be an array to use the Multisite trait.',
static::class
));
}
$this->bindEvent('model.beforeSave', [$this, 'multisiteBeforeSave']);
$this->bindEvent('model.afterCreate', [$this, 'multisiteAfterCreate']);
$this->bindEvent('model.saveComplete', [$this, 'multisiteSaveComplete']);
$this->bindEvent('model.afterDelete', [$this, 'multisiteAfterDelete']);
$this->defineMultisiteRelations();
}
/**
* multisiteBeforeSave constructor event used internally
*/
public function multisiteBeforeSave()
{
if (Site::hasGlobalContext()) {
return;
}
$this->{$this->getSiteIdColumn()} = Site::getSiteIdFromContext();
}
/**
* multisiteSaveComplete constructor event used internally
*/
public function multisiteSaveComplete()
{
if ($this->getSaveOption('propagate') !== true) {
return;
}
if (!$this->isMultisiteEnabled()) {
return;
}
Site::withGlobalContext(function() {
$otherModels = $this->newOtherSiteQuery()->get();
$otherSites = $this->getMultisiteSyncSites();
// Propagate attributes to known records
if ($this->propagatable) {
foreach ($otherSites as $siteId) {
if ($model = $otherModels->where('site_id', $siteId)->first()) {
$this->propagateToSite($siteId, $model);
}
}
}
// Sync non-existent records
if ($this->isMultisiteSyncEnabled()) {
$missingSites = array_diff($otherSites, $otherModels->pluck('site_id')->all());
foreach ($missingSites as $missingSite) {
$this->propagateToSite($missingSite);
}
}
});
}
/**
* multisiteAfterCreate constructor event used internally
*/
public function multisiteAfterCreate()
{
if ($this->site_root_id) {
return;
}
$this->site_root_id = $this->id;
$this->newQueryWithoutScopes()
->where($this->getKeyName(), $this->id)
->update(['site_root_id' => $this->site_root_id])
;
}
/**
* multisiteAfterDelete
*/
public function multisiteAfterDelete()
{
if (!$this->isMultisiteSyncEnabled() || !$this->getMultisiteConfig('delete', true)) {
return;
}
Site::withGlobalContext(function() {
foreach ($this->getMultisiteSyncSites() as $siteId) {
if (!$this->isModelUsingSameSite($siteId)) {
$this->deleteForSite($siteId);
}
}
});
}
/**
* defineMultisiteRelations will spin over every relation and apply propagation config
*/
protected function defineMultisiteRelations()
{
foreach ($this->getRelationDefinitions() as $type => $relations) {
foreach ($this->$type as $name => $definition) {
if ($this->isAttributePropagatable($name)) {
$this->defineMultisiteRelation($name, $type);
}
}
}
}
/**
* canDeleteMultisiteRelation checks if a relation has the potential to be shared with
* the current model. If there are 2 or more records in existence, then this method
* will prevent the cascading deletion of relations.
*
* @see \October\Rain\Database\Concerns\HasRelationships::performDeleteOnRelations
*/
public function canDeleteMultisiteRelation($name, $type = null): bool
{
// Attribute is exclusive to parent model without propagation
if (!$this->isAttributePropagatable($name)) {
return true;
}
if ($type === null) {
$type = $this->getRelationType($name);
}
// Type is not supported by multisite
if (!in_array($type, ['belongsToMany', 'morphToMany', 'morphedByMany', 'belongsTo', 'hasOne', 'hasMany', 'attachOne', 'attachMany'])) {
return true;
}
// The current record counts for one so halt if we find more
return !($this->newOtherSiteQuery()->count() > 1);
}
/**
* defineMultisiteRelation will modify defined relations on this model so they share
* their association using the shared identifier (`site_root_id`). Only these relation
* types support relation sharing: `belongsToMany`, `morphToMany`, `morphedByMany`,
* `belongsTo`, `hasOne`, `hasMany`, `attachOne`, `attachMany`.
*/
protected function defineMultisiteRelation($name, $type = null)
{
if ($type === null) {
$type = $this->getRelationType($name);
}
if ($type) {
if (!is_array($this->$type[$name])) {
$this->$type[$name] = (array) $this->$type[$name];
}
// Override the local key to the shared root identifier
if (in_array($type, ['belongsToMany', 'morphToMany', 'morphedByMany'])) {
$this->$type[$name]['parentKey'] = 'site_root_id';
}
elseif (in_array($type, ['belongsTo', 'hasOne', 'hasMany'])) {
$this->$type[$name]['otherKey'] = 'site_root_id';
}
elseif (in_array($type, ['attachOne', 'attachMany'])) {
$this->$type[$name]['key'] = 'site_root_id';
}
}
}
/**
* savePropagate the model, including to other sites
* @return bool
*/
public function savePropagate($options = null, $sessionKey = null)
{
return $this->saveInternal((array) $options + ['propagate' => true, 'sessionKey' => $sessionKey]);
}
/**
* addPropagatable attributes for the model.
* @param array|string|null $attributes
*/
public function addPropagatable($attributes = null)
{
$attributes = is_array($attributes) ? $attributes : func_get_args();
$this->propagatable = array_merge($this->propagatable, $attributes);
foreach ($attributes as $attribute) {
$this->defineMultisiteRelation($attribute);
}
}
/**
* isAttributePropagatable
* @return bool
*/
public function isAttributePropagatable($attribute)
{
return in_array($attribute, $this->propagatable);
}
/**
* propagateToSite will save propagated fields to other records
*/
public function propagateToSite($siteId, $otherModel = null)
{
if ($this->isModelUsingSameSite($siteId)) {
return;
}
if ($otherModel === null) {
$otherModel = $this->findOtherSiteModel($siteId);
}
// Perform propagation for existing records
if ($otherModel->exists) {
foreach ($this->propagatable as $name) {
$relationType = $this->getRelationType($name);
// Propagate local key relation
if ($relationType === 'belongsTo') {
$fkName = $this->$name()->getForeignKeyName();
$otherModel->$fkName = $this->$fkName;
}
// Propagate local attribute (not a relation)
elseif (!$relationType) {
$otherModel->$name = $this->$name;
}
}
}
$otherModel->save(['force' => true]);
return $otherModel;
}
/**
* getMultisiteKey returns the root key if multisite is used
*/
public function getMultisiteKey()
{
if (!$this->isMultisiteEnabled()) {
return $this->getKey();
}
return $this->site_root_id ?: $this->getKey();
}
/**
* isMultisiteEnabled allows for programmatic toggling
* @return bool
*/
public function isMultisiteEnabled()
{
return true;
}
/**
* isMultisiteSyncEnabled
*/
public function isMultisiteSyncEnabled()
{
if (!property_exists($this, 'propagatableSync')) {
return false;
}
if (is_array($this->propagatableSync)) {
return ($this->propagatableSync['sync'] ?? false) !== false;
}
return (bool) $this->propagatableSync;
}
/**
* getMultisiteConfig
*/
public function getMultisiteConfig($key, $default = null)
{
if (!property_exists($this, 'propagatableSync') || !is_array($this->propagatableSync)) {
return $default;
}
return Arr::get($this->propagatableSync, $key, $default);
}
/**
* getMultisiteSyncSites
* @return array
*/
public function getMultisiteSyncSites()
{
if ($this->getMultisiteConfig('sync') === 'all') {
return Site::listSiteIds();
}
$siteId = $this->{$this->getSiteIdColumn()} ?: null;
if ($this->getMultisiteConfig('sync') === 'locale') {
return Site::listSiteIdsInLocale($siteId);
}
return Site::listSiteIdsInGroup($siteId);
}
/**
* scopeApplyOtherSiteRoot is used to resolve a model using its ID or its root ID.
* For example, finding a model using attributes from another site, or finding
* all connected models for all sites.
*
* If the value is provided as a string, it must be the ID from the primary record,
* in other words: taken from `site_root_id` not from the `id` column.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param string|\Illuminate\Database\Eloquent\Model $idOrModel
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeApplyOtherSiteRoot($query, $idOrModel)
{
if ($idOrModel instanceof \Illuminate\Database\Eloquent\Model) {
$idOrModel = $idOrModel->site_root_id ?: $idOrModel->id;
}
return $query->where(function($q) use ($idOrModel) {
$q->where('id', $idOrModel);
$q->orWhere('site_root_id', $idOrModel);
});
}
/**
* newOtherSiteQuery
*/
public function newOtherSiteQuery()
{
return $this->newQueryWithoutScopes()->applyOtherSiteRoot($this);
}
/**
* findForSite will locate a record for a specific site.
*/
public function findForSite($siteId = null)
{
return $this
->newOtherSiteQuery()
->where($this->getSiteIdColumn(), $siteId)
->first();
}
/**
* findOrCreateForSite
*/
public function findOrCreateForSite($siteId = null)
{
$otherModel = $this->findOtherSiteModel($siteId);
// Newly created model
if (!$otherModel->exists) {
$otherModel->save(['force' => true]);
}
// Restoring a trashed model
if (
$otherModel->isClassInstanceOf(\October\Contracts\Database\SoftDeleteInterface::class) &&
$otherModel->trashed()
) {
$otherModel->restore();
}
return $otherModel;
}
/**
* findOtherSiteModel
*/
protected function findOtherSiteModel($siteId = null)
{
if ($siteId === null) {
$siteId = Site::getSiteIdFromContext();
}
if ($this->isModelUsingSameSite($siteId)) {
return $this;
}
$otherModel = $this->findForSite($siteId);
// Replicate without save
if (!$otherModel) {
$otherModel = $this->replicateWithRelations($this->getMultisiteConfig('except'));
$otherModel->{$this->getSiteIdColumn()} = $siteId;
$otherModel->site_root_id = $this->site_root_id ?: $this->id;
}
return $otherModel;
}
/**
* deleteForSite runs the delete command on a model for another site, useful for cleaning
* up records for other sites when the parent is deleted.
*/
public function deleteForSite($siteId = null)
{
$otherModel = $this->findForSite($siteId);
if (!$otherModel) {
return;
}
$useSoftDeletes = $this->isClassInstanceOf(\October\Contracts\Database\SoftDeleteInterface::class);
if ($useSoftDeletes && !$this->isSoftDelete()) {
static::withoutEvents(function() use ($otherModel) {
$otherModel->forceDelete();
});
return;
}
static::withoutEvents(function() use ($otherModel) {
$otherModel->delete();
});
}
/**
* isModelUsingSameSite
*/
protected function isModelUsingSameSite($siteId = null)
{
return (int) $this->{$this->getSiteIdColumn()} === (int) $siteId;
}
/**
* getSiteIdColumn gets the name of the "site id" column.
* @return string
*/
public function getSiteIdColumn()
{
return defined('static::SITE_ID') ? static::SITE_ID : 'site_id';
}
/**
* getQualifiedSiteIdColumn gets the fully qualified "site id" column.
* @return string
*/
public function getQualifiedSiteIdColumn()
{
return $this->qualifyColumn($this->getSiteIdColumn());
}
}