forked from silverstripe/silverstripe-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCMSBatchAction.php
206 lines (181 loc) · 6.71 KB
/
CMSBatchAction.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
<?php
namespace SilverStripe\Admin;
use SilverStripe\CMS\Controllers\CMSMain;
use SilverStripe\CMS\Model\SiteTree;
use SilverStripe\Control\Controller;
use SilverStripe\Control\HTTPResponse;
use SilverStripe\Core\Convert;
use SilverStripe\Core\Injector\Injectable;
use SilverStripe\Model\List\SS_List;
use SilverStripe\ORM\DataObject;
use SilverStripe\Versioned\Versioned;
/**
* A class representing back actions.
* See CMSMain.BatchActions.js on how to add custom javascript
* functionality.
*
* <code>
* CMSMain::register_batch_action('publishitems', new CMSBatchAction('doPublish',
* _t('CMSBatchActions.PUBLISHED_PAGES', 'published %d pages')));
* </code>
*/
abstract class CMSBatchAction
{
use Injectable;
protected $managedClass = SiteTree::class;
/**
* The the text to show in the dropdown for this action
*/
abstract public function getActionTitle();
/**
* Run this action for the given set of pages.
* Return a set of status-updated JavaScript to return to the CMS.
*
* @param SS_List $objs
* @return string
*/
abstract public function run(SS_List $objs): HTTPResponse;
/**
* Helper method for responding to a back action request
* @param string $successMessage The message to return as a notification.
* Can have up to two %d's in it. The first will be replaced by the number of successful
* changes, the second by the number of failures
* @param array $status A status array like batchactions builds. Should be
* key => value pairs, the key can be any string: "error" indicates errors, anything
* else indicates a type of success. The value is an array. We don't care what's in it,
* we just use count($value) to find the number of items that succeeded or failed
*/
public function response($successMessage, $status): HTTPResponse
{
$count = 0;
$errors = 0;
foreach ($status as $k => $v) {
switch ($k) {
case 'error':
$errors += count($v ?? []);
break;
case 'success':
$count += count($v ?? []);
break;
}
}
return HTTPResponse::create()
->setStatusCode(200, sprintf($successMessage ?? '', $count, $errors))
->setBody(json_encode($status));
}
/**
* Helper method for processing batch actions.
* Returns a set of status-updating JavaScript to return to the CMS.
*
* @param SS_List $objs The SS_List of objects to perform this batch action
* on.
* @param string $helperMethod The method to call on each of those objects.
* @param string $successMessage
* @param array $arguments
* @return HTTPResponse with a body set to JSON encoded map in the following format:
* {
* 'modified': {
* 3: {'TreeTitle': 'Page3'},
* 5: {'TreeTitle': 'Page5'}
* },
* 'deleted': {
* // all deleted pages
* }
* }
*/
public function batchaction(SS_List $objs, $helperMethod, $successMessage, $arguments = []): HTTPResponse
{
$status = ['modified' => [], 'error' => [], 'deleted' => [], 'success' => []];
foreach ($objs as $obj) {
// Perform the action
$id = $obj->ID;
if (!call_user_func_array([$obj, $helperMethod], $arguments ?? [])) {
$status['error'][$id] = $id;
} else {
$status['success'][$id] = $id;
}
// Now make sure the tree title is appropriately updated
$publishedRecord = DataObject::get_by_id($this->managedClass, $id);
if ($publishedRecord instanceof SiteTree) {
$treeTitle = CMSMain::singleton()->getRecordTreeMarkup($publishedRecord);
} else {
$treeTitle = $publishedRecord->TreeTitle;
}
if ($publishedRecord) {
$status['modified'][$id] = [
'TreeTitle' => $treeTitle,
];
} else {
$status['deleted'][$id] = $id;
}
$obj->destroy();
unset($obj);
}
return $this->response($successMessage, $status);
}
/**
* Helper method for applicablePages() methods. Acts as a skeleton implementation.
*
* @param array $ids The IDs passed to applicablePages
* @param string $methodName The canXXX() method to call on each page to check if the action is applicable
* @param bool $checkStagePages Set to true if you want to check stage pages
* @param bool $checkLivePages Set to true if you want to check live pages (e.g, for deleted-from-draft)
* @return array
*/
public function applicablePagesHelper($ids, $methodName, $checkStagePages = true, $checkLivePages = true)
{
if (!is_array($ids)) {
user_error("Bad \$ids passed to applicablePagesHelper()", E_USER_WARNING);
}
if (!is_string($methodName)) {
user_error("Bad \$methodName passed to applicablePagesHelper()", E_USER_WARNING);
}
$applicableIDs = [];
$managedClass = $this->managedClass;
$draftPages = DataObject::get($managedClass)->byIDs($ids);
// Filter out the live-only ids
$onlyOnLive = array_fill_keys($ids ?? [], true);
if ($checkStagePages) {
foreach ($draftPages as $obj) {
unset($onlyOnLive[$obj->ID]);
if ($obj->$methodName()) {
$applicableIDs[] = $obj->ID;
}
}
}
$onlyOnLive = array_keys($onlyOnLive ?? []);
if ($checkLivePages && $onlyOnLive && DataObject::has_extension($managedClass, Versioned::class)) {
// Get the pages that only exist on live (deleted from stage)
$livePages = Versioned::get_by_stage($managedClass, "Live")->byIDs($onlyOnLive);
foreach ($livePages as $obj) {
if ($obj->$methodName()) {
$applicableIDs[] = $obj->ID;
}
}
}
return $applicableIDs;
}
// if your batchaction has parameters, return a FieldList here
public function getParameterFields()
{
return false;
}
/**
* If you wish to restrict the batch action to some users, overload this function.
*/
public function canView()
{
return true;
}
/**
* Given a list of object IDs, filter out which items can have this batch action applied
* to them.
*
* @param array $ids List of object ids
* @return array Filtered list of $ids
*/
public function applicablePages($ids)
{
return $ids;
}
}