You are here

function simplenews_user_presave in Simplenews 8

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

Implements hook_user_presave().

User data (mail, status, language) and all configurable fields are synchronized with subscriber.

This function handles existing user account, simplenews_user_insert takes care of new accounts.

See also

simplenews_user_insert()

File

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

Code

function simplenews_user_presave(UserInterface $account) {

  // Don't do anything if the user has no email.
  if (!$account
    ->getEmail()) {
    return;
  }

  /** @var \Drupal\simplenews\Entity\Subscriber $subscriber */
  $subscriber = $account
    ->isNew() ? simplenews_subscriber_load_by_mail($account
    ->getEmail()) : simplenews_subscriber_load_by_uid($account
    ->id());
  if ($subscriber && !$subscriber
    ->isSyncing()) {
    $subscriber
      ->setSyncing();

    // We only process existing accounts.
    if (!$account
      ->isNew()) {

      // Update mail, status and language if they are changed.
      $subscriber
        ->setMail($account
        ->getEmail());
      $subscriber->status = $account
        ->isActive();
      $subscriber
        ->setLangcode($account
        ->getPreferredLangcode());
    }

    // Copy values for shared fields to existing subscriber.
    if (\Drupal::config('simplenews.settings')
      ->get('subscriber.sync_fields')) {
      foreach ($subscriber
        ->getUserSharedFields($account) as $field_name) {
        $subscriber
          ->set($field_name, $account
          ->get($field_name)
          ->getValue());
      }
    }
    $subscriber
      ->save();
    $subscriber
      ->setSyncing(FALSE);
  }
}