You are here

public function OpignoMessageThread::sendEmailToThreadMembers in Opigno messaging 3.x

Send the email to all thread members when the new message is created.

Parameters

\Drupal\private_message\Entity\PrivateMessageThreadInterface $thread: The PM thread.

\Drupal\private_message\Entity\PrivateMessageInterface $message: The message.

File

src/Services/OpignoMessageThread.php, line 355

Class

OpignoMessageThread
The private messages manager service.

Namespace

Drupal\opigno_messaging\Services

Code

public function sendEmailToThreadMembers(PrivateMessageThreadInterface $thread, PrivateMessageInterface $message) : void {
  $members = $thread
    ->getMembers();
  if (!$members) {
    return;
  }
  $pm_config = $this->config
    ->get('private_message.settings');
  $message_notification_mail_map = $this->config
    ->getEditable('private_message.mail')
    ->get('message_notification');
  $site_name = $this->config
    ->get('system.site')
    ->get('name') ?? 'Opigno';
  $params = [
    'private_message' => $message,
    'private_message_thread' => $thread,
    'subject' => str_replace('[site:name]', $site_name, $message_notification_mail_map['subject']),
  ];
  $thread_url = Url::fromRoute('entity.private_message_thread.canonical', [
    'private_message_thread' => $thread
      ->id(),
  ])
    ->setAbsolute();
  $thread_link = Link::fromTextAndUrl($thread_url
    ->toString(), $thread_url)
    ->toString();

  // Send email notifications for members.
  foreach ($members as $member) {
    if (!$member instanceof UserInterface || (int) $member
      ->id() === (int) $this->account
      ->id()) {
      continue;
    }
    $params['member'] = $member;
    $send = $this->userData
      ->get('private_message', $member
      ->id(), 'email_notification');
    $send = is_numeric($send) ? (bool) $send : $pm_config
      ->get('enable_email_notifications') && $pm_config
      ->get('send_by_default');
    if (!$send) {
      continue;
    }
    $user_name = $member
      ->getDisplayName();
    $author_name = $message
      ->getOwner()
      ->getDisplayName();
    $message = $message
      ->getMessage();
    $params['message'] = str_replace([
      '[site:name]',
      '[user:display-name]',
      '[private_message:author-name]',
      '[private_message:message]',
      '[private_message_thread:url]',
    ], [
      '<strong>' . $site_name . '</strong>',
      '<strong>' . $user_name . '</strong>',
      '<strong>' . $author_name . '</strong>',
      '<strong>' . $message . '</strong>',
      '<strong>' . $thread_link . '</strong>',
    ], $message_notification_mail_map['body']);
    $this->mailService
      ->mail('opigno_messaging', 'message_notification', $member
      ->getEmail(), $member
      ->getPreferredLangcode(), $params);
  }
}