-
Notifications
You must be signed in to change notification settings - Fork 611
/
ResaveController.php
630 lines (553 loc) · 19.4 KB
/
ResaveController.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
623
624
625
626
627
628
629
630
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\console\controllers;
use Craft;
use craft\base\Element;
use craft\base\ElementInterface;
use craft\console\Controller;
use craft\elements\Address;
use craft\elements\Asset;
use craft\elements\Category;
use craft\elements\db\ElementQuery;
use craft\elements\db\ElementQueryInterface;
use craft\elements\Entry;
use craft\elements\Tag;
use craft\elements\User;
use craft\errors\InvalidElementException;
use craft\events\MultiElementActionEvent;
use craft\helpers\ElementHelper;
use craft\helpers\Queue;
use craft\helpers\StringHelper;
use craft\models\Site;
use craft\queue\jobs\ResaveElements;
use craft\services\Elements;
use Throwable;
use yii\console\ExitCode;
use yii\helpers\Console;
/**
* Allows you to bulk-save elements.
*
* See [Bulk-Resaving Elements](https://craftcms.com/knowledge-base/bulk-resaving-elements) for examples.
*
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 3.1.15
*/
class ResaveController extends Controller
{
/**
* Returns [[to]] normalized to a callable.
*
* @param string|null $to
* @return callable
* @since 4.2.6
* @internal
*/
final public static function normalizeTo(?string $to): callable
{
// empty
if ($to === ':empty:') {
return function() {
return '';
};
}
// object template
if (str_starts_with($to, '=')) {
$template = substr($to, 1);
$view = Craft::$app->getView();
return function(ElementInterface $element) use ($template, $view) {
return $view->renderObjectTemplate($template, $element);
};
}
// PHP arrow function
if (preg_match('/^fn\s*\(\s*(?:\$(\w+)\s*)?\)\s*=>\s*(.+)/', $to, $match)) {
$var = $match[1];
$php = sprintf('return %s;', StringHelper::removeLeft(rtrim($match[2], ';'), 'return '));
return function(ElementInterface $element) use ($var, $php) {
if ($var) {
$$var = $element;
}
return eval($php);
};
}
// attribute name
return static function(ElementInterface $element) use ($to) {
return $element->$to;
};
}
/**
* @var bool Whether the elements should be resaved via a queue job.
* @since 3.7.0
*/
public bool $queue = false;
/**
* @var bool Whether to resave element drafts.
* @since 3.6.5
*/
public bool $drafts = false;
/**
* @var bool Whether to resave provisional element drafts.
* @since 3.7.0
*/
public bool $provisionalDrafts = false;
/**
* @var bool Whether to resave element revisions.
* @since 3.7.35
*/
public bool $revisions = false;
/**
* @var int|string|null The ID(s) of the elements to resave.
*/
public string|int|null $elementId = null;
/**
* @var string|null The UUID(s) of the elements to resave.
*/
public ?string $uid = null;
/**
* @var string|null The site handle to fetch elements from.
*/
public ?string $site = null;
/**
* @var string|int[]|null Comma-separated site handles to propagate entries to.
*
* When this is set, the entry will *only* be saved for this site.
*
* @since 4.4.7
*/
public string|array|null $propagateTo = null;
/**
* @var string The status(es) of elements to resave. Can be set to multiple comma-separated statuses.
*/
public string $status = 'any';
/**
* @var int|null The number of elements to skip.
*/
public ?int $offset = null;
/**
* @var int|null The number of elements to resave.
*/
public ?int $limit = null;
/**
* @var bool Whether to update the search indexes for the resaved elements.
*/
public bool $updateSearchIndex = false;
/**
* @var bool Whether to update the `dateUpdated` timestamp for the elements.
* @since 4.2.4
*/
public bool $touch = false;
/**
* @var string|null The group handle(s) to save categories/tags/users from. Can be set to multiple comma-separated groups.
*/
public ?string $group = null;
/**
* @var string|null The section handle(s) to save entries from. Can be set to multiple comma-separated sections.
*/
public ?string $section = null;
/**
* @var string|null The type handle(s) of the elements to resave.
* @since 3.1.16
*/
public ?string $type = null;
/**
* @var string|null The volume handle(s) to save assets from. Can be set to multiple comma-separated volumes.
*/
public ?string $volume = null;
/**
* @var string|null The field handle to save nested entries for.
*/
public ?string $field = null;
/**
* @var string|int[]|null Comma-separated list of owner element IDs.
* @since 4.5.6
*/
public string|array|null $ownerId = null;
/**
* @var string|null Comma-separated list of country codes.
* @since 4.5.6
*/
public ?string $countryCode = null;
/**
* @var string|null An attribute name that should be set for each of the elements. The value will be determined by --to.
* @since 3.7.29
*/
public ?string $set = null;
/**
* @var bool|null The site-enabled status that should be set on the entry, for the site it’s initially being saved/propagated to.
* @since 4.4.7
*/
public ?bool $setEnabledForSite = null;
/**
* @var string|null The value that should be set on the --set attribute.
*
* The following value types are supported:
* - An attribute name: `--to myCustomField`
* - An object template: `--to "={myCustomField|lower}"`
* - A raw value: `--to "=foo bar"`
* - A PHP arrow function: `--to "fn(\\$element) => \\$element->callSomething()"`
* - An empty value: `--to :empty:`
*
* @since 3.7.29
*/
public ?string $to = null;
/**
* @var bool Whether the `--set` attribute should only be set if it doesn’t have a value.
* @since 3.7.29
*/
public bool $ifEmpty = false;
/**
* @var bool Whether the `--set` attribute should only be set if the current value doesn’t validate.
* @since 4.9.0
*/
public bool $ifInvalid = false;
/**
* @inheritdoc
*/
public function options($actionID): array
{
$options = parent::options($actionID);
$options[] = 'queue';
$options[] = 'elementId';
$options[] = 'uid';
$options[] = 'site';
$options[] = 'status';
$options[] = 'offset';
$options[] = 'limit';
$options[] = 'updateSearchIndex';
$options[] = 'touch';
switch ($actionID) {
case 'addresses':
$options[] = 'ownerId';
$options[] = 'countryCode';
break;
case 'assets':
$options[] = 'volume';
break;
case 'tags':
case 'users':
case 'categories':
$options[] = 'group';
break;
case 'entries':
$options[] = 'section';
$options[] = 'field';
$options[] = 'ownerId';
$options[] = 'type';
$options[] = 'drafts';
$options[] = 'provisionalDrafts';
$options[] = 'revisions';
$options[] = 'propagateTo';
$options[] = 'setEnabledForSite';
break;
}
$options[] = 'set';
$options[] = 'to';
$options[] = 'ifEmpty';
$options[] = 'ifInvalid';
return $options;
}
/**
* @inheritdoc
*/
public function beforeAction($action): bool
{
if (!parent::beforeAction($action)) {
return false;
}
if (isset($this->propagateTo)) {
$siteHandles = array_filter(StringHelper::split($this->propagateTo));
$this->propagateTo = [];
$sitesService = Craft::$app->getSites();
foreach ($siteHandles as $siteHandle) {
$site = $sitesService->getSiteByHandle($siteHandle, true);
if (!$site) {
$this->stderr("Invalid site handle: $siteHandle" . PHP_EOL, Console::FG_RED);
return false;
}
$this->propagateTo[] = $site->id;
}
if (isset($this->set)) {
$this->stderr('--propagate-to can’t be coupled with --set.' . PHP_EOL, Console::FG_RED);
return false;
}
}
if (isset($this->set) && !isset($this->to)) {
$this->stderr('--to is required when using --set.' . PHP_EOL, Console::FG_RED);
return false;
}
return true;
}
/**
* Re-saves user addresses.
*
* @return int
* @since 4.5.6
*/
public function actionAddresses(): int
{
$criteria = [];
if (isset($this->ownerId)) {
$criteria['ownerId'] = array_map(fn(string $id) => (int)$id, explode(',', (string)$this->ownerId));
}
if (isset($this->countryCode)) {
$criteria['countryCode'] = explode(',', (string)$this->countryCode);
}
return $this->resaveElements(Address::class, $criteria);
}
/**
* Re-saves assets.
*
* @return int
*/
public function actionAssets(): int
{
$criteria = [];
if (isset($this->volume)) {
$criteria['volume'] = explode(',', $this->volume);
}
return $this->resaveElements(Asset::class, $criteria);
}
/**
* Re-saves categories.
*
* @return int
*/
public function actionCategories(): int
{
$criteria = [];
if (isset($this->group)) {
$criteria['group'] = explode(',', $this->group);
}
return $this->resaveElements(Category::class, $criteria);
}
/**
* Re-saves entries.
*
* @return int
*/
public function actionEntries(): int
{
$criteria = [];
if (isset($this->section)) {
$criteria['section'] = explode(',', $this->section);
}
if (isset($this->field)) {
$criteria['field'] = explode(',', $this->field);
}
if (isset($this->ownerId)) {
$criteria['ownerId'] = array_map(fn(string $id) => (int)$id, explode(',', (string)$this->ownerId));
}
if (isset($this->type)) {
$criteria['type'] = explode(',', $this->type);
}
return $this->resaveElements(Entry::class, $criteria);
}
/**
* Re-saves tags.
*
* @return int
*/
public function actionTags(): int
{
$criteria = [];
if (isset($this->group)) {
$criteria['group'] = explode(',', $this->group);
}
return $this->resaveElements(Tag::class, $criteria);
}
/**
* Re-saves users.
*
* @return int
*/
public function actionUsers(): int
{
$criteria = [];
if (isset($this->group)) {
$criteria['group'] = explode(',', $this->group);
}
return $this->resaveElements(User::class, $criteria);
}
/**
* @param string $elementType The element type that should be resaved
* @phpstan-param class-string<ElementInterface> $elementType
* @param array $criteria The element criteria that determines which elements should be resaved
* @return int
* @since 3.7.0
*/
public function resaveElements(string $elementType, array $criteria = []): int
{
/** @var string|ElementInterface $elementType */
/** @phpstan-var class-string<ElementInterface>|ElementInterface $elementType */
$criteria += $this->_baseCriteria();
if ($this->queue) {
Queue::push(new ResaveElements([
'elementType' => $elementType,
'criteria' => $criteria,
'set' => $this->set,
'to' => $this->to,
'ifEmpty' => $this->ifEmpty,
'ifInvalid' => $this->ifInvalid,
'touch' => $this->touch,
'updateSearchIndex' => $this->updateSearchIndex,
]));
$this->stdout($elementType::pluralDisplayName() . ' queued to be resaved.' . PHP_EOL);
return ExitCode::OK;
}
$query = $elementType::find();
Craft::configure($query, $criteria);
return $this->_resaveElements($query);
}
/**
* @param ElementQueryInterface $query
* @return int
* @since 3.2.0
* @deprecated in 3.7.0. Use [[resaveElements()]] instead.
*/
public function saveElements(ElementQueryInterface $query): int
{
if ($this->queue) {
$this->stderr('This command doesn’t support the --queue option yet.' . PHP_EOL, Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
Craft::configure($query, $this->_baseCriteria());
return $this->_resaveElements($query);
}
/**
* @return array
*/
private function _baseCriteria(): array
{
$criteria = [];
if ($this->drafts) {
$criteria['drafts'] = true;
}
if ($this->provisionalDrafts) {
$criteria['drafts'] = true;
$criteria['provisionalDrafts'] = true;
}
if ($this->revisions) {
$criteria['revisions'] = true;
}
if ($this->elementId) {
$criteria['id'] = is_int($this->elementId) ? $this->elementId : explode(',', $this->elementId);
}
if ($this->uid) {
$criteria['uid'] = explode(',', $this->uid);
}
if ($this->site) {
$criteria['site'] = $this->site;
}
if ($this->status === 'any') {
$criteria['status'] = null;
} elseif ($this->status) {
$criteria['status'] = explode(',', $this->status);
}
if (isset($this->offset)) {
$criteria['offset'] = $this->offset;
}
if (isset($this->limit)) {
$criteria['limit'] = $this->limit;
}
return $criteria;
}
/**
* Resave elements
*/
private function _resaveElements(ElementQueryInterface $query): int
{
/** @var ElementQuery $query */
/** @var ElementInterface $elementType */
$elementType = $query->elementType;
$count = (int)$query->count();
if ($count === 0) {
$this->stdout('No ' . $elementType::pluralLowerDisplayName() . ' exist for that criteria.' . PHP_EOL, Console::FG_YELLOW);
return ExitCode::OK;
}
if ($query->offset) {
$count = max($count - (int)$query->offset, 0);
}
if ($query->limit) {
$count = min($count, (int)$query->limit);
}
$to = isset($this->set) ? self::normalizeTo($this->to) : null;
$label = isset($this->propagateTo) ? 'Propagating' : 'Resaving';
$elementsText = $count === 1 ? $elementType::lowerDisplayName() : $elementType::pluralLowerDisplayName();
$this->stdout("$label $count $elementsText ..." . PHP_EOL, Console::FG_YELLOW);
$elementsService = Craft::$app->getElements();
$fail = false;
$beforeCallback = function(MultiElementActionEvent $e) use ($query, $count, $to) {
if ($e->query === $query) {
$label = isset($this->propagateTo) ? 'Propagating' : 'Resaving';
$element = $e->element;
$this->stdout(" - [$e->position/$count] $label $element ($element->id) ... ");
if (isset($this->propagateTo)) {
// Set the full array for all sites, so the propagated element gets the right status
$siteStatuses = ElementHelper::siteStatusesForElement($element);
foreach ($this->propagateTo as $siteId) {
$siteStatuses[$siteId] = $this->setEnabledForSite ?? $siteStatuses[$siteId] ?? $element->getEnabledForSite();
}
$element->setEnabledForSite($siteStatuses);
} else {
if (isset($this->setEnabledForSite)) {
// Just set it for this site
$element->setEnabledForSite($this->setEnabledForSite);
}
try {
if (isset($this->set)) {
$set = true;
if ($this->ifEmpty) {
if (!ElementHelper::isAttributeEmpty($element, $this->set)) {
$set = false;
}
} elseif ($this->ifInvalid) {
$element->setScenario(Element::SCENARIO_LIVE);
if ($element->validate($this->set) && $element->validate("field:$this->set")) {
$set = false;
}
}
if ($set) {
$element->{$this->set} = $to($element);
}
}
} catch (Throwable $e) {
throw new InvalidElementException($element, $e->getMessage());
}
}
}
};
$afterCallback = function(MultiElementActionEvent $e) use ($query, &$fail) {
if ($e->query === $query) {
$element = $e->element;
if ($e->exception) {
$this->stderr('error: ' . $e->exception->getMessage() . PHP_EOL, Console::FG_RED);
$fail = true;
} elseif ($element->hasErrors()) {
$this->stderr('failed: ' . implode(', ', $element->getErrorSummary(true)) . PHP_EOL, Console::FG_RED);
$fail = true;
} else {
$this->stdout('done' . PHP_EOL, Console::FG_GREEN);
}
}
};
if (isset($this->propagateTo)) {
$elementsService->on(Elements::EVENT_BEFORE_PROPAGATE_ELEMENT, $beforeCallback);
$elementsService->on(Elements::EVENT_AFTER_PROPAGATE_ELEMENT, $afterCallback);
$elementsService->propagateElements($query, $this->propagateTo, true);
$elementsService->off(Elements::EVENT_BEFORE_PROPAGATE_ELEMENT, $beforeCallback);
$elementsService->off(Elements::EVENT_AFTER_PROPAGATE_ELEMENT, $afterCallback);
} else {
$elementsService->on(Elements::EVENT_BEFORE_RESAVE_ELEMENT, $beforeCallback);
$elementsService->on(Elements::EVENT_AFTER_RESAVE_ELEMENT, $afterCallback);
$elementsService->resaveElements($query, true, !$this->revisions, $this->updateSearchIndex, $this->touch);
$elementsService->off(Elements::EVENT_BEFORE_RESAVE_ELEMENT, $beforeCallback);
$elementsService->off(Elements::EVENT_AFTER_RESAVE_ELEMENT, $afterCallback);
}
$label = isset($this->propagateTo) ? 'propagating' : 'resaving';
$this->stdout("Done $label $elementsText." . PHP_EOL . PHP_EOL, Console::FG_YELLOW);
return $fail ? ExitCode::UNSPECIFIED_ERROR : ExitCode::OK;
}
}