Skip to content
Snippets Groups Projects
Commit d123da17 authored by Steve Wirt's avatar Steve Wirt
Browse files

Merge branch '3425031-add-script-example' into '1.0.x'

Issue #3425031: Add script example for node operation

See merge request !28
parents e42a54e8 344cc651
No related branches found
No related tags found
No related merge requests found
Pipeline #349823 passed with warnings
<?php
namespace Drupal\codit_batch_operations\cbo_scripts;
use Drupal\codit_batch_operations\BatchOperations;
use Drupal\codit_batch_operations\BatchScriptInterface;
/**
* An example Batch Operation to show archiving old nodes based on date by cron.
*/
class ExampleArchiveOldNodes extends BatchOperations implements BatchScriptInterface {
/**
* {@inheritdoc}
*/
public function getTitle():string {
return 'Archive old news node items';
}
/**
* {@inheritdoc}
*/
public function getDescription():string {
$description = <<<ENDHERE
News items that have not been updated in more than a year old should be
archived as they are no longer news. This handles that using cron.
ENDHERE;
return $description;
}
/**
* {@inheritdoc}
*/
public function getCompletedMessage(): string {
return 'Archived @completed out of @total news items.';
}
/**
* Optionally name the main type of thing being operated on.
*
* Suggestions: node, term, menu_item, block, bundle name, user, etc.
*
* If you do not define this, it defaults to 'item'.
*
* @return string
* The string that will be used to prefix items in the logging.
*/
public function getItemType(): string {
return 'node:news';
}
/**
* {@inheritdoc}
*/
public function gatherItemsToProcess(): array {
$time_to_archive_before = strtotime("- 1 year");
$query = $this->entityTypeManager->getStorage('node')->getQuery();
$query->condition('type', 'news', '=')
// Only get published items that have not been touched in a year.
->condition('changed', $time_to_archive_before, '<=')
->condition( 'status' , 1)
->accessCheck(FALSE);
$results = $query->execute();
// Remove the revision ids (keys) from the Node ids (values).
$items = array_values($results);
return $items;
}
/**
* {@inheritdoc}
*/
public function processOne(string $key, mixed $item, array &$sandbox): string {
$node = $this->getNodeLatestRevision((int) $item);
$node->set('moderation_state', 'archived');
$revision_log_message = 'Archived this News item because it was over a year since the last update.';
$create_new_revision = TRUE;
$this->saveNodeRevision($node, $revision_log_message, $create_new_revision);
return "/node/{$item} Archived '{$node->getTitle()}'.";
}
/**
* {@inheritdoc}
*/
public function getCronTiming(): string | array {
// Consult the README for supported patterns.
// We only want this to run once per month.
return ['on the 1st of every 1 month'];
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment