You are here

function simplenews_user_presave in Simplenews 3.x

Same name and namespace in other branches
  1. 8.2 simplenews.module \simplenews_user_presave()
  2. 8 simplenews.module \simplenews_user_presave()
  3. 7.2 simplenews.module \simplenews_user_presave()
  4. 7 simplenews.module \simplenews_user_presave()

Implements hook_ENTITY_TYPE_presave() for user entity.

If the user is subscribed, update the subscriber from the account.

File

./simplenews.module, line 463
Simplenews node handling, sent email, newsletter block and general hooks.

Code

function simplenews_user_presave(UserInterface $account) {

  // New accounts have no ID when this hook is called and instead are handled
  // in simplenews_user_insert.
  if ($account
    ->isNew()) {
    return;
  }

  // We need to handle the case that the account email has changed.
  $subscriber = Subscriber::loadByUid($account
    ->id());
  $new_subscriber = Subscriber::loadByMail($account
    ->getEmail());
  if ($subscriber) {
    if ($new_subscriber && $new_subscriber
      ->id() != $subscriber
      ->id()) {

      // The account has a subscription and the new email address matches a
      // different subscription: keep the existing subscription, and delete
      // the different one.
      $new_subscriber
        ->delete();
    }
    $subscriber
      ->fillFromAccount($account)
      ->save();
  }
  elseif ($new_subscriber) {

    // The account currently has no subscription and the new email address
    // matches an existing subscription: link that subscription.
    $new_subscriber
      ->fillFromAccount($account)
      ->save();
  }
}