Skip to content

Instantly share code, notes, and snippets.

@svetlio
Last active February 13, 2024 14:20
Show Gist options
  • Save svetlio/cbbd64033323981e8a3fb9159fad2f73 to your computer and use it in GitHub Desktop.
Save svetlio/cbbd64033323981e8a3fb9159fad2f73 to your computer and use it in GitHub Desktop.
post_update batch
<?php
/**
* Update existing nodes cp property to false.
*/
function uneo_pcf_cp_post_update_node_cp_prop(&$sandbox) {
$entity_type_id = 'node';
$id_name = 'nid';
_update_entity_cp_property($sandbox, $entity_type_id, $id_name);
}
/**
* Update existing taxonomy terms cp property to false.
*/
function uneo_pcf_cp_post_update_taxonomy_term_cp_prop(&$sandbox) {
$entity_type_id = 'taxonomy_term';
$id_name = 'tid';
_update_entity_cp_property($sandbox, $entity_type_id, $id_name);
}
function _update_entity_cp_property(&$sandbox, $entity_type_id, $id_name) {
$etm = \Drupal::entityTypeManager();
$etm_storage = $etm->getStorage($entity_type_id);
if (empty($sandbox)) {
$query = $etm_storage->getQuery();
$query->accessCheck(FALSE);
$ids = $query->execute();
$sandbox['progress'] = 0;
$sandbox['current_id'] = 0;
$sandbox['max'] = count($ids);
}
if (!$sandbox['max']) {
$sandbox['#finished'] = 1;
return;
}
$limit = 5;
$query = $etm_storage->getQuery();
$query->accessCheck(FALSE);
$query->sort($id_name);
$query->condition($id_name, $sandbox['current_id'], '>');
$query->range(0, $limit);
$ids = $query->execute();
foreach ($ids AS $id) {
$entity = $etm_storage->load($id);
$value = $entity->get('cp')->getValue();
if (isset($value[0]['value']) && $value[0]['value']) {
$entity->get('cp')->setValue(FALSE);
$entity->save();
}
$sandbox['results'][] = $entity->id();
$sandbox['progress']++;
$sandbox['current_id'] = $entity->id();
$sandbox['message'] = $entity_type_id . ': ' . $entity->id();
}
//\Drupal::messenger()->addMessage('processed : ' . json_encode($ids));
//\Drupal::logger('uneo_pcf_cp')->debug('Progress: ' . $sandbox['progress'] . ' items processed. ' . $entity_type_id);
\Drupal::logger('uneo_pcf_cp')->debug('current batch chunk: ' . json_encode(array_values($ids)));
$sandbox['#finished'] = ($sandbox['progress'] / $sandbox['max']); // 1
// Print some progress.
return t('@count items processed.', ['@count' => $sandbox['progress']]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment