-
Notifications
You must be signed in to change notification settings - Fork 611
/
NestedElementsController.php
177 lines (154 loc) · 5.78 KB
/
NestedElementsController.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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\controllers;
use Craft;
use craft\base\ElementInterface;
use craft\base\NestedElementInterface;
use craft\db\Table;
use craft\elements\db\ElementQueryInterface;
use craft\elements\ElementCollection;
use craft\helpers\Db;
use craft\web\Controller;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\Response;
/**
* Nested elements controller.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 5.0.0
*/
class NestedElementsController extends Controller
{
private ElementInterface $owner;
private ElementQueryInterface|ElementCollection $nestedElements;
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
if (!parent::beforeAction($action)) {
return false;
}
$this->requireCpRequest();
// Get the owner element
/** @var ElementInterface|string $ownerElementType */
$ownerElementType = $this->request->getRequiredBodyParam('ownerElementType');
$ownerId = $this->request->getRequiredBodyParam('ownerId');
$ownerSiteId = $this->request->getRequiredBodyParam('ownerSiteId');
$owner = Craft::$app->getElements()->getElementById($ownerId, $ownerElementType, $ownerSiteId);
if (!$owner) {
throw new BadRequestHttpException('Invalid owner params');
}
$this->owner = $owner;
// Make sure they're authorized to manage it
$session = Craft::$app->getSession();
$attribute = $this->request->getRequiredBodyParam('attribute');
if (
!$session->checkAuthorization(sprintf('manageNestedElements::%s::%s', $owner->id, $attribute)) &&
(
$owner->id === $owner->getCanonicalId() ||
!$session->checkAuthorization(sprintf('manageNestedElements::%s::%s', $owner->getCanonicalId(), $attribute))
)
) {
throw new ForbiddenHttpException('User is not authorized to perform this action');
}
// Set the nested elements for the action
$this->nestedElements = $this->owner->$attribute;
return true;
}
/**
* Moves the given elements to a new starting offset
*
* @return Response
*/
public function actionReorder(): Response
{
$ids = array_map(fn($id) => (int)$id, $this->request->getRequiredBodyParam('elementIds'));
$offset = $this->request->getRequiredBodyParam('offset');
if ($this->nestedElements instanceof ElementQueryInterface) {
$oldSortOrders = (clone $this->nestedElements)
->asArray()
->select(['id', 'sortOrder'])
->pairs();
} else {
$oldSortOrders = $this->nestedElements
->keyBy(fn(ElementInterface $element) => $element->id)
/** @phpstan-ignore-next-line */
->map(fn(NestedElementInterface $element) => $element->getSortOrder())
->all();
}
// Build the full list of IDs in the new sort order
$allIds = array_diff(array_keys($oldSortOrders), $ids);
array_splice($allIds, $offset, 0, $ids);
// Update all the incorrect sort orders
foreach ($allIds as $i => $id) {
$sortOrder = $i + 1;
if (!isset($oldSortOrders[$id]) || $sortOrder !== $oldSortOrders[$id]) {
Db::update(Table::ELEMENTS_OWNERS, [
'sortOrder' => $sortOrder,
], [
'ownerId' => $this->owner->id,
'elementId' => $id,
]);
}
}
Craft::$app->getElements()->invalidateCachesForElement($this->owner);
return $this->asSuccess(Craft::t('app', 'New {total, plural, =1{position} other{positions}} saved.', [
'total' => count($ids),
]));
}
/**
* Deletes a given element.
*
* @return Response
*/
public function actionDelete(): Response
{
$elementId = (int)$this->request->getRequiredBodyParam('elementId');
if ($this->nestedElements instanceof ElementQueryInterface) {
$element = $this->nestedElements
->id($elementId)
->status(null)
->drafts(null)
->provisionalDrafts(null)
->one();
} else {
$element = $this->nestedElements->first(
fn(ElementInterface $element) => (
$element->id === $elementId ||
$element->getCanonicalId() === $elementId
)
);
}
if (!$element) {
throw new BadRequestHttpException('Invalid elementId param');
}
$elementsService = Craft::$app->getElements();
if (!$elementsService->canDelete($element)) {
throw new ForbiddenHttpException('User not authorized to delete this element.');
}
// If the element primarily belongs to a different element, just delete the ownership
if ($element->getPrimaryOwnerId() !== $this->owner->id) {
Db::delete(Table::ELEMENTS_OWNERS, [
'elementId' => $element->id,
'ownerId' => $this->owner->id,
]);
$success = true;
} else {
$success = $elementsService->deleteElement($element);
}
if (!$success) {
return $this->asFailure(Craft::t('app', 'Couldn’t delete {type}.', [
'type' => $element::lowerDisplayName(),
]));
}
return $this->asSuccess(Craft::t('app', '{type} deleted.', [
'type' => $element::displayName(),
]));
}
}