SocialProfilePrivacyBatchHelper.php in Open Social 10.3.x
File
modules/social_features/social_profile/modules/social_profile_privacy/src/Service/SocialProfilePrivacyBatchHelper.php
View source
<?php
namespace Drupal\social_profile_privacy\Service;
use Drupal\Core\Batch\BatchBuilder;
use Drupal\profile\Entity\ProfileInterface;
class SocialProfilePrivacyBatchHelper {
public static function bulkUpdateProfileNames() {
$profile_storage = \Drupal::entityTypeManager()
->getStorage('profile');
$pids = $profile_storage
->getQuery()
->accessCheck(FALSE)
->execute();
$batch_builder = (new BatchBuilder())
->setTitle(t('Updating profile names...'))
->setFinishCallback([
SocialProfilePrivacyBatchHelper::class,
'finishProcess',
])
->addOperation([
SocialProfilePrivacyBatchHelper::class,
'updateProcess',
], [
$pids,
]);
batch_set($batch_builder
->toArray());
}
public static function updateProcess(array $items, array &$context) {
$limit = 50;
if (empty($context['sandbox']['progress'])) {
$context['sandbox']['progress'] = 0;
$context['sandbox']['max'] = count($items);
}
if (empty($context['sandbox']['items'])) {
$context['sandbox']['items'] = $items;
}
if (!empty($context['sandbox']['items'])) {
$profile_storage = \Drupal::entityTypeManager()
->getStorage('profile');
$current_pids = array_splice($context['sandbox']['items'], 0, $limit);
$profiles = $profile_storage
->loadMultiple($current_pids);
foreach ($profiles as $profile) {
if ($profile instanceof ProfileInterface) {
SocialProfilePrivacyBatchHelper::updateProfileName($profile);
}
$context['sandbox']['progress']++;
$context['message'] = t('Now processing profile :progress of :count', [
':progress' => $context['sandbox']['progress'],
':count' => $context['sandbox']['max'],
]);
$context['results']['processed'] = $context['sandbox']['progress'];
}
}
if ($context['sandbox']['progress'] != $context['sandbox']['max']) {
$context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max'];
}
}
public static function finishProcess($success, array $results, array $operations) {
$message = t('Number of profiles affected by batch: @count', [
'@count' => $results['processed'],
]);
\Drupal::messenger()
->addStatus($message);
}
public static function updateProfileName(ProfileInterface $profile) {
if ($profile instanceof ProfileInterface) {
$profile_name_service = \Drupal::service('social_profile.name_service');
$profile_name = $profile_name_service
->getProfileName($profile);
$profile
->set('profile_name', $profile_name);
$profile
->save();
}
}
}