-
Notifications
You must be signed in to change notification settings - Fork 645
/
Copy pathStructures.php
622 lines (536 loc) · 19.8 KB
/
Structures.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
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
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\services;
use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\db\Query;
use craft\db\Table;
use craft\errors\MutexException;
use craft\errors\StructureNotFoundException;
use craft\events\MoveElementEvent;
use craft\models\Structure;
use craft\records\Structure as StructureRecord;
use craft\records\StructureElement;
use Throwable;
use yii\base\Component;
use yii\base\Exception;
/**
* Structures service.
*
* An instance of the service is available via [[\craft\base\ApplicationTrait::getStructures()|`Craft::$app->structures`]].
*
* @author Pixel & Tonic, Inc. <[email protected]>
* @since 3.0.0
*/
class Structures extends Component
{
/**
* @event MoveElementEvent The event that is triggered before an element is inserted into a structure.
*
* You may set [[\yii\base\ModelEvent::$isValid]] to `false` to prevent the
* element from getting inserted.
*
* @since 4.5.0
*/
public const EVENT_BEFORE_INSERT_ELEMENT = 'beforeInsertElement';
/**
* @event MoveElementEvent The event that is triggered after an element is inserted into a structure.
* @since 4.5.0
*/
public const EVENT_AFTER_INSERT_ELEMENT = 'afterInsertElement';
/**
* @event MoveElementEvent The event that is triggered before an element is moved.
*
* In Craft 4.5 and later, you may set [[\yii\base\ModelEvent::$isValid]] to `false` to prevent the
* element from getting moved.
*/
public const EVENT_BEFORE_MOVE_ELEMENT = 'beforeMoveElement';
/**
* @event MoveElementEvent The event that is triggered after an element is moved.
*/
public const EVENT_AFTER_MOVE_ELEMENT = 'afterMoveElement';
/** @since 3.4.21 */
public const MODE_INSERT = 'insert';
/** @since 3.4.21 */
public const MODE_UPDATE = 'update';
/** @since 3.4.21 */
public const MODE_AUTO = 'auto';
/** @since 4.5.0 */
public const ACTION_PREPEND = 'prepend';
/** @since 4.5.0 */
public const ACTION_APPEND = 'append';
/** @since 4.5.0 */
public const ACTION_PLACE_BEFORE = 'placeBefore';
/** @since 4.5.0 */
public const ACTION_PLACE_AFTER = 'placeAfter';
/**
* @var int The timeout to pass to [[\yii\mutex\Mutex::acquire()]] when acquiring a lock on the structure.
* @since 3.0.19
*/
public int $mutexTimeout = 3;
/**
* @var StructureElement[]
*/
private array $_rootElementRecordsByStructureId = [];
// Structure CRUD
// -------------------------------------------------------------------------
/**
* Returns a structure by its ID.
*
* @param int $structureId
* @param bool $withTrashed
* @return Structure|null
*/
public function getStructureById(int $structureId, bool $withTrashed = false): ?Structure
{
$query = (new Query())
->select([
'id',
'maxLevels',
'uid',
])
->from([Table::STRUCTURES])
->where(['id' => $structureId]);
if (!$withTrashed) {
$query->andWhere(['dateDeleted' => null]);
}
$result = $query->one();
return $result ? new Structure($result) : null;
}
/**
* Returns a structure by its UID.
*
* @param string $structureUid
* @param bool $withTrashed
* @return Structure|null
*/
public function getStructureByUid(string $structureUid, bool $withTrashed = false): ?Structure
{
$query = (new Query())
->select([
'id',
'maxLevels',
'uid',
])
->from([Table::STRUCTURES])
->where(['uid' => $structureUid]);
if (!$withTrashed) {
$query->andWhere(['dateDeleted' => null]);
}
$result = $query->one();
return $result ? new Structure($result) : null;
}
/**
* Patches an array of entries, filling in any gaps in the tree.
*
* @param ElementInterface[] $elements
* @since 3.6.0
*/
public function fillGapsInElements(array &$elements): void
{
/** @var ElementInterface|null $prevElement */
$prevElement = null;
$patchedElements = [];
// https://github.com/craftcms/cms/issues/16085
// don't assume that elements are in the top to bottom order
usort($elements, fn(ElementInterface $a, ElementInterface $b) => $a->lft <=> $b->lft);
foreach ($elements as $i => $element) {
// Did we just skip any elements?
if (
$element->level != 1 &&
(
$i == 0 ||
(!$element->isSiblingOf($prevElement) && !$element->isChildOf($prevElement))
)
) {
// Merge in any missing ancestors
$ancestorQuery = $element->getAncestors()
->status(null);
if ($prevElement) {
$ancestorQuery->andWhere(['>', 'structureelements.lft', $prevElement->lft]);
}
foreach ($ancestorQuery->all() as $ancestor) {
$patchedElements[] = $ancestor;
}
}
$patchedElements[] = $element;
$prevElement = $element;
}
$elements = $patchedElements;
}
/**
* Filters an array of elements down to only <= X branches.
*
* @param ElementInterface[] $elements
* @param int $branchLimit
* @since 3.6.0
*/
public function applyBranchLimitToElements(array &$elements, int $branchLimit): void
{
$branchCount = 0;
$prevElement = null;
foreach ($elements as $i => $element) {
// Is this a new branch?
if ($prevElement === null || !$element->isDescendantOf($prevElement)) {
$branchCount++;
// Have we gone over?
if ($branchCount > $branchLimit) {
array_splice($elements, $i);
break;
}
}
$prevElement = $element;
}
}
/**
* Saves a structure
*
* @param Structure $structure
* @return bool Whether the structure was saved successfully
* @throws StructureNotFoundException if $structure->id is invalid
*/
public function saveStructure(Structure $structure): bool
{
if ($structure->id) {
/** @var StructureRecord|null $structureRecord */
$structureRecord = StructureRecord::findWithTrashed()
->andWhere(['id' => $structure->id])
->one();
if (!$structureRecord) {
throw new StructureNotFoundException("No structure exists with the ID '$structure->id'");
}
} else {
$structureRecord = new StructureRecord();
}
$structureRecord->maxLevels = $structure->maxLevels;
$structureRecord->uid = $structure->uid;
if ($structureRecord->dateDeleted) {
$success = $structureRecord->restore();
} else {
$success = $structureRecord->save();
}
if ($success) {
$structure->id = $structureRecord->id;
} else {
$structure->addErrors($structureRecord->getErrors());
}
return $success;
}
/**
* Deletes a structure by its ID.
*
* @param int $structureId
* @return bool
*/
public function deleteStructureById(int $structureId): bool
{
if (!$structureId) {
return false;
}
$affectedRows = Craft::$app->getDb()->createCommand()
->softDelete(Table::STRUCTURES, [
'id' => $structureId,
])
->execute();
return (bool)$affectedRows;
}
/**
* Returns the descendant level delta for a given element.
*
* @param int $structureId
* @param ElementInterface $element
* @return int
*/
public function getElementLevelDelta(int $structureId, ElementInterface $element): int
{
$elementRecord = $this->_getElementRecord($structureId, $element);
/** @var StructureElement|null $deepestDescendant */
$deepestDescendant = $elementRecord
->children()
->orderBy(['level' => SORT_DESC])
->one();
if ($deepestDescendant) {
return $deepestDescendant->level - $elementRecord->level;
}
return 0;
}
// Moving elements around
// -------------------------------------------------------------------------
/**
* Prepends an element to another within a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @param int|ElementInterface $parentElement
* @param string $mode Whether this is an "insert", "update", or "auto".
* @return bool
* @throws Exception
*/
public function prepend(int $structureId, ElementInterface $element, ElementInterface|int $parentElement, string $mode = self::MODE_AUTO): bool
{
$parentElementRecord = $this->_getElementRecord($structureId, $parentElement);
if ($parentElementRecord === null) {
throw new Exception('There was a problem getting the parent element.');
}
return $this->_doIt($structureId, $element, $parentElementRecord, self::ACTION_PREPEND, $mode);
}
/**
* Appends an element to another within a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @param int|ElementInterface $parentElement
* @param string $mode Whether this is an "insert", "update", or "auto".
* @return bool
* @throws Exception
*/
public function append(int $structureId, ElementInterface $element, ElementInterface|int $parentElement, string $mode = self::MODE_AUTO): bool
{
$parentElementRecord = $this->_getElementRecord($structureId, $parentElement);
if ($parentElementRecord === null) {
throw new Exception('There was a problem getting the parent element.');
}
return $this->_doIt($structureId, $element, $parentElementRecord, self::ACTION_APPEND, $mode);
}
/**
* Prepends an element to the root of a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @param string $mode Whether this is an "insert", "update", or "auto".
* @return bool
* @throws Exception
*/
public function prependToRoot(int $structureId, ElementInterface $element, string $mode = self::MODE_AUTO): bool
{
$parentElementRecord = $this->_getRootElementRecord($structureId);
return $this->_doIt($structureId, $element, $parentElementRecord, self::ACTION_PREPEND, $mode);
}
/**
* Appends an element to the root of a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @param string $mode Whether this is an "insert", "update", or "auto".
* @return bool
* @throws Exception
*/
public function appendToRoot(int $structureId, ElementInterface $element, string $mode = self::MODE_AUTO): bool
{
$parentElementRecord = $this->_getRootElementRecord($structureId);
return $this->_doIt($structureId, $element, $parentElementRecord, self::ACTION_APPEND, $mode);
}
/**
* Moves an element before another within a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @param int|ElementInterface $nextElement
* @param string $mode Whether this is an "insert", "update", or "auto".
* @return bool
* @throws Exception
*/
public function moveBefore(int $structureId, ElementInterface $element, ElementInterface|int $nextElement, string $mode = self::MODE_AUTO): bool
{
$nextElementRecord = $this->_getElementRecord($structureId, $nextElement);
if ($nextElementRecord === null) {
throw new Exception('There was a problem getting the next element.');
}
return $this->_doIt($structureId, $element, $nextElementRecord, self::ACTION_PLACE_BEFORE, $mode);
}
/**
* Moves an element after another within a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @param int|ElementInterface $prevElement
* @param string $mode Whether this is an "insert", "update", or "auto".
* @return bool
* @throws Exception
*/
public function moveAfter(int $structureId, ElementInterface $element, ElementInterface|int $prevElement, string $mode = self::MODE_AUTO): bool
{
$prevElementRecord = $this->_getElementRecord($structureId, $prevElement);
if ($prevElementRecord === null) {
throw new Exception('There was a problem getting the previous element.');
}
return $this->_doIt($structureId, $element, $prevElementRecord, self::ACTION_PLACE_AFTER, $mode);
}
/**
* Removes an element from a given structure.
*
* @param int $structureId
* @param ElementInterface $element
* @return bool
* @throws Exception
* @since 3.7.19
*/
public function remove(int $structureId, ElementInterface $element): bool
{
$elementRecord = $this->_getElementRecord($structureId, $element);
if ($elementRecord && !$elementRecord->delete()) {
return false;
}
$element->root = null;
$element->lft = null;
$element->rgt = null;
$element->level = null;
return true;
}
/**
* Returns a structure element record from given structure and element IDs.
*
* @param int $structureId
* @param int|ElementInterface $element
* @return StructureElement|null
*/
private function _getElementRecord(int $structureId, ElementInterface|int $element): ?StructureElement
{
$elementId = is_numeric($element) ? $element : $element->id;
if ($elementId) {
return StructureElement::findOne([
'structureId' => $structureId,
'elementId' => $elementId,
]);
}
return null;
}
/**
* Returns the root node for a given structure ID, or creates one if it doesn't exist.
*
* @param int $structureId
* @return StructureElement
*/
private function _getRootElementRecord(int $structureId): StructureElement
{
if (!isset($this->_rootElementRecordsByStructureId[$structureId])) {
/** @var StructureElement|null $elementRecord */
$elementRecord = StructureElement::find()
->where(['structureId' => $structureId])
->roots()
->one();
if (!$elementRecord) {
// Create it
$elementRecord = new StructureElement();
$elementRecord->structureId = $structureId;
$elementRecord->makeRoot();
}
$this->_rootElementRecordsByStructureId[$structureId] = $elementRecord;
}
return $this->_rootElementRecordsByStructureId[$structureId];
}
/**
* Updates a ElementInterface with the new structure attributes from a StructureElement record.
*
* @param int $structureId
* @param ElementInterface $element
* @param StructureElement $targetElementRecord
* @param self::ACTION_* $action
* @param self::MODE_* $mode
* @return bool Whether it was done
* @throws Throwable if reasons
*/
private function _doIt(int $structureId, ElementInterface $element, StructureElement $targetElementRecord, string $action, string $mode): bool
{
// Get a lock or bust
$lockName = 'structure:' . $structureId;
$mutex = Craft::$app->getMutex();
if (!$mutex->acquire($lockName, $this->mutexTimeout)) {
throw new MutexException($lockName, sprintf('Unable to acquire a lock for the structure %s', $structureId));
}
$elementRecord = null;
/** @var Element $element */
// Figure out what we're doing
if ($mode !== self::MODE_INSERT) {
// See if there's an existing structure element record
$elementRecord = $this->_getElementRecord($structureId, $element);
if ($elementRecord !== null) {
$mode = self::MODE_UPDATE;
}
}
if ($elementRecord === null) {
$elementRecord = new StructureElement();
$elementRecord->structureId = $structureId;
$elementRecord->elementId = $element->id;
$mode = self::MODE_INSERT;
}
[$beforeEvent, $afterEvent] = match ($mode) {
self::MODE_INSERT => [self::EVENT_BEFORE_INSERT_ELEMENT, self::EVENT_AFTER_INSERT_ELEMENT],
self::MODE_UPDATE => [self::EVENT_BEFORE_MOVE_ELEMENT, self::EVENT_AFTER_MOVE_ELEMENT],
};
$targetElementId = $targetElementRecord->isRoot() ? null : $targetElementRecord->elementId;
// Fire a 'beforeInsertElement' or 'beforeMoveElement' event
if ($this->hasEventHandlers($beforeEvent)) {
$event = new MoveElementEvent([
'element' => $element,
'structureId' => $structureId,
'targetElementId' => $targetElementId,
'action' => $action,
]);
$this->trigger($beforeEvent, $event);
if (!$event->isValid) {
$mutex->release($lockName);
return false;
}
}
// Tell the element about it
if (!$element->beforeMoveInStructure($structureId)) {
$mutex->release($lockName);
return false;
}
$method = match ($action) {
self::ACTION_PREPEND => 'prependTo',
self::ACTION_APPEND => 'appendTo',
self::ACTION_PLACE_BEFORE => 'insertBefore',
self::ACTION_PLACE_AFTER => 'insertAfter',
};
$transaction = Craft::$app->getDb()->beginTransaction();
try {
if (!$elementRecord->$method($targetElementRecord)) {
$transaction->rollBack();
$mutex->release($lockName);
return false;
}
$mutex->release($lockName);
// Update the element with the latest values.
// todo: we should be able to pull these from $elementRecord - https://github.com/creocoder/yii2-nested-sets/issues/114
$values = (new Query())
->select(['root', 'lft', 'rgt', 'level'])
->from(Table::STRUCTUREELEMENTS)
->where([
'structureId' => $structureId,
'elementId' => $element->id,
])
->one();
$element->root = $values['root'];
$element->lft = $values['lft'];
$element->rgt = $values['rgt'];
$element->level = $values['level'];
// Tell the element about it
$element->afterMoveInStructure($structureId);
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
$mutex->release($lockName);
throw $e;
}
// Invalidate all caches for the element type
// (see https://github.com/craftcms/cms/issues/14846)
Craft::$app->getElements()->invalidateCachesForElementType($element::class);
if ($this->hasEventHandlers($afterEvent)) {
// Fire an 'afterMoveElement' event
$this->trigger($afterEvent, new MoveElementEvent([
'element' => $element,
'structureId' => $structureId,
'targetElementId' => $targetElementId,
'action' => $action,
]));
}
return true;
}
}