You are here

function contact_emails_mail_alter in Contact Emails 8

Implements hook_mail_alter().

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

File

./contact_emails.module, line 35
Contains contact_emails.module..

Code

function contact_emails_mail_alter(&$message) {

  // If an email from the contact module, disable sending.
  $contact_form_ids = [
    'contact_page_autoreply',
    'contact_page_mail',
  ];
  if (in_array($message['id'], $contact_form_ids)) {

    /** @var \Drupal\contact\MessageInterface $contact_message */
    if ($contact_message = $message['params']['contact_message']) {
      $contact_form = $contact_message
        ->getContactForm();
      $contact_form_id = $contact_form
        ->id();

      /** @var \Drupal\contact_emails\ContactEmailStorageInterface $storage */
      $storage = \Drupal::entityTypeManager()
        ->getStorage('contact_email');
      if ($storage
        ->hasContactEmails($contact_form_id)) {

        // Disable sending of default mails if we have at least one email
        // set by contact_emails (regardless of whether or not it is a disabled
        // email).
        $message['send'] = FALSE;
      }
    }
    else {

      // If we don't have a contact_message object, something must have gone
      // wrong, let's disable just in case.
      $log = t('Unable to load the contact message when attempting to alter the default mailing from contact form for contact form id: @contact_form_id', [
        '@contact_form_id' => $message['id'],
      ]);
      \Drupal::logger('contact_emails')
        ->notice($log);
      $message['send'] = FALSE;
    }
  }
}