You are here

function user_badges_user_presave in User Badges 8

Same name and namespace in other branches
  1. 7 user_badges.module \user_badges_user_presave()

Implements hook_ENTITY_TYPE_presave().

File

./user_badges.module, line 39
Contains user_badges.module..

Code

function user_badges_user_presave(Drupal\Core\Entity\EntityInterface $entity) {

  /** @var \Drupal\user\Entity\User $entity */
  $account_role_ids = $entity
    ->getRoles();
  $field_item_list = $entity
    ->get('field_user_badges');
  foreach ($field_item_list
    ->filterEmptyItems() as $index => $item) {

    /** @var \Drupal\user_badges\Entity\Badge $badge */
    $badge = $item
      ->get('entity')
      ->getValue();
    $badge_role_ids = $badge
      ->getBadgeRoleIds();

    // Remove the badge if it has roles but none among the current ones.
    if ($badge_role_ids && !array_intersect($badge_role_ids, $account_role_ids)) {
      $field_item_list
        ->removeItem($index);
    }
    else {
      $target_ids[] = $badge
        ->id();
    }
  }

  // Add the rest.
  $query = \Drupal::entityQuery('badge')
    ->condition('role_id', $account_role_ids, 'IN');
  if (!empty($target_ids)) {
    $query
      ->condition('id', $target_ids, 'NOT IN');
  }
  array_map([
    $field_item_list,
    'appendItem',
  ], $query
    ->execute());
}