function opigno_messaging_update_9002 in Opigno messaging 3.x
Set the author and the group checkbox to old PM threads.
File
- ./
opigno_messaging.install, line 115 - Install, update and uninstall functions for the Opigno Messaging module.
Code
function opigno_messaging_update_9002(&$sandbox) {
// Prepare the batch data.
if (empty($sandbox['entity_list'])) {
try {
$entity_list = \Drupal::entityTypeManager()
->getStorage('private_message_thread')
->loadMultiple();
} catch (PluginNotFoundException|InvalidPluginDefinitionException $e) {
watchdog_exception('opigno_messaging_exception', $e);
return t('Something went wrong, update failed.');
}
if (!$entity_list) {
return t('No private message threads to update, finish.');
}
$sandbox['total'] = count($entity_list);
$sandbox['entity_list'] = array_chunk($entity_list, 50);
$sandbox['succeeded'] = $sandbox['errored'] = $sandbox['processed_chunks'] = 0;
}
// Clear the memory cache to avoid the update failing because of the memory
// lack.
$cache = \Drupal::service('entity.memory_cache');
if ($cache instanceof MemoryCache) {
$cache
->deleteAll();
}
// Here is where we process all of the items.
$current_chunk = $sandbox['entity_list'][$sandbox['processed_chunks']];
foreach ($current_chunk as $thread) {
if (!$thread instanceof PrivateMessageThreadInterface || count($thread
->getMembers()) <= 2 || !$thread
->hasField('field_author') || !$thread
->hasField('field_create_group')) {
continue;
}
// Get the 1st message to set the thread author.
$messages = $thread
->getMessages();
foreach ($messages as $message) {
if ($message instanceof PrivateMessageInterface) {
$thread
->set('field_author', $message
->getOwnerId());
break;
}
}
// Set the group checkbox.
$thread
->set('field_create_group', TRUE);
try {
$thread
->save();
$sandbox['succeeded']++;
} catch (EntityStorageException $e) {
$sandbox['errored']++;
watchdog_exception('opigno_messaging_exception', $e);
}
}
$sandbox['processed_chunks']++;
$sandbox['#finished'] = $sandbox['processed_chunks'] / count($sandbox['entity_list']);
// Display the batch result.
if ($sandbox['#finished'] === 1) {
return t('@succeeded private message threads were processed correctly. @errored entities failed.', [
'@succeeded' => $sandbox['succeeded'],
'@errored' => $sandbox['errored'],
]);
}
}