Commit 8d9a6612 authored by Melissa Bent's avatar Melissa Bent
Browse files

Issue #3262133 by merauluka: Add custom logging and email notifications to...

Issue #3262133 by merauluka: Add custom logging and email notifications to trace validation successes and failures.
parent b8f98851
Loading
Loading
Loading
Loading
+65 −0
Original line number Diff line number Diff line
@@ -42,6 +42,10 @@ function byteplant_email_validation(&$form, FormStateInterface $form_state) {

function byteplant_email_validation_process_fields(&$form, FormStateInterface $form_state, $valid_status) {
  $email_validator = \Drupal::service('byteplant_email_validation');
  $logging_options = \Drupal::config('byteplant_email_validation.byteplant_settings')->get('logging');
  $logging_options = array_filter($logging_options);
  $logger = \Drupal::logger('byteplant_email_validation');
  $mail_manager = \Drupal::service('plugin.manager.mail');
  foreach ($form as $id => $element) {
    if (is_array($element) && isset($element['#type'])) {
      if ($element['#type'] == 'container') {
@@ -60,9 +64,70 @@ function byteplant_email_validation_process_fields(&$form, FormStateInterface $f
            !in_array($content->status, $valid_status)
          ) {
            $form_state->setErrorByName($id, $email_validator->getMessage($content));
            if (in_array('error', $logging_options)) {
              $logger->error('The email, @email, failed validation. Response: <pre><code>@response</code></pre>', [
                '@email' => $email,
                '@response' => var_export($content, TRUE),
              ]);
            }
            if (in_array('email_error', $logging_options)) {
              $langcode = \Drupal::currentUser()->getPreferredLangcode();
              $site_config = \Drupal::config('system.site');
              $params = [
                'message' => t('The email, @email, failed validation. Response: <pre><code>@response</code></pre>', [
                  '@email' => $email,
                  '@response' => var_export($content, TRUE),
                ])->__toString(),
              ];
              $mail_manager->mail('byteplant_email_validation', 'validation_error', $site_config->get('mail'), $langcode, $params);
            }
          }
          else {
            if (in_array('success', $logging_options)) {
              $logger->info('The email, @email, was validated successfully. Response: <pre><code>@response</code></pre>', [
                '@email' => $email,
                '@response' => var_export($content, TRUE),
              ]);
            }
            if (in_array('email_success', $logging_options)) {
              $langcode = \Drupal::currentUser()->getPreferredLangcode();
              $site_config = \Drupal::config('system.site');
              $params = [
                'message' => t('The email, @email, was validated successfully. Response: <pre><code>@response</code></pre>', [
                  '@email' => $email,
                  '@response' => var_export($content, TRUE),
                ])->__toString(),
              ];
              $mail_manager->mail('byteplant_email_validation', 'validation_success', $site_config->get('mail'), $langcode, $params);
            }
          }
        }
      }
    }
  }
}

/**
* Implements hook_mail().
*/
function byteplant_email_validation_mail($key, &$message, $params) {
  $options = array(
    'langcode' => $message['langcode'],
  );

  switch ($key) {
    case 'validation_error':
      $site_config = \Drupal::config('system.site');
      $message['from'] = $site_config->get('mail');
      $message['subject'] = t('@site_name: Email validation failed', ['@site_name' => $site_config->get('name')], $options);
      $message['body'][] = $params['message'];
      break;

    case 'validation_success':
      $site_config = \Drupal::config('system.site');
      $message['from'] = $site_config->get('mail');
      $message['subject'] = t('@site_name: Email validation succeeded', ['@site_name' => $site_config->get('name')], $options);
      $message['body'][] = $params['message'];
      break;
  }
 }
+5 −1
Original line number Diff line number Diff line
services:
  byteplant_email_validation:
    class: Drupal\byteplant_email_validation\EmailValidationService
    arguments: ['@config.factory', '@http_client']
    arguments: ['@config.factory', '@http_client', '@logger.channel.byteplant_email_validation', '@plugin.manager.mail']

  logger.channel.byteplant_email_validation:
    parent: logger.channel_base
    arguments: ['byteplant_email_validation']
+22 −0
Original line number Diff line number Diff line
byteplant_email_validation.settings:
  type: config_object
  label: 'Byteplant Email Validation settings.'
  mapping:
    key:
      type: string
      label: 'Email validation API Key'
    url:
      type: string
      label: 'Email validation URL'
    forms:
      type: string
      label: 'Protected forms'
    message:
      type: string
      label: 'Custom error message'
    logging:
      type: sequence
      label: 'Logging options'
      sequence:
        type: string
        label: 'Logging option'
+43 −13
Original line number Diff line number Diff line
@@ -4,6 +4,7 @@ namespace Drupal\byteplant_email_validation;

use Drupal\Core\Config\ConfigFactoryInterface;
use GuzzleHttp\Client;
use Psr\Log\LoggerInterface;

/**
 * Class EmailValidationService.
@@ -26,24 +27,42 @@ class EmailValidationService {
   */
  protected $httpClient;

  /**
   * The Byteplant Email Validation logger.
   *
   * @var Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * The array of configured events that should produce logs.
   *
   * @var array
   */
  protected $loggingOptions;

  /**
   * Constructs an EmailValidation object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param GuzzleHttp\Client $http_client
   * @param \GuzzleHttp\Client $http_client
   *   The guzzle http client.
   *
   * @param \Psr\Log\LoggerInterface $logger
   *   The Byteplant Email Validation logger.
   */
  public function __construct(ConfigFactoryInterface $config_factory, Client $httpClient) {
  public function __construct(ConfigFactoryInterface $config_factory, Client $http_client, LoggerInterface $logger) {
    $this->config = $config_factory->get('byteplant_email_validation.byteplant_settings');
    $this->httpClient = $httpClient;
    $this->httpClient = $http_client;
    $this->logger = $logger;
    $this->loggingOptions = array_filter($this->config->get('logging'));
  }

  /**
   * Get request using guzzle client.
   *
   * @return mixed|string
   * @return object
   *   The returned response from Byteplant or an empty object on error.
   */
  public function verifyEmail($email) {
    // Get Byteplant Key and url by form.
@@ -51,13 +70,21 @@ class EmailValidationService {
    $url = $this->config->get('url');
    $query = 'EmailAddress=' . $email . '&APIKey=' . $key;
    $url = $url . '?' . $query;
    return $this->getRequest($url);
    if (in_array('request', $this->loggingOptions)) {
      $this->logger->info('The email @email is being submitted for validation.', ['@email' => $email]);
    }
    $response = $this->getRequest($url);
    if (in_array('request', $this->loggingOptions)) {
      $this->logger->info('The email @email was successfully submitted for validation.', ['@email' => $email]);
    }
    return $response;
  }

  /**
   * Get Invalidate email message.
   * Get invalid email message to display on user forms.
   *
   * @return mixed|string
   * @return string
   *   The error message to display to the end user.
   */
  public function getMessage($content) {
    // If user set message then use it, else use byteplant status.
@@ -70,12 +97,15 @@ class EmailValidationService {
  /**
   * Get Email validation details from BytePlant service.
   *
   * @param $url
   * @param null $options
   * @param string $url
   *   The url to use when making the request to byteplant.
   * @param array $options
   *   The array of options to include with the HTTP request to byteplant.
   *
   * @return mixed|string
   * @return object
   *   The returned response from Byteplant or an empty object on error.
   */
  public function getRequest($url, $options = NULL) {
  public function getRequest(string $url, array $options = []) {
    try {
      $client = $this->httpClient;
      $request = $client->get($url, $options);
@@ -84,7 +114,7 @@ class EmailValidationService {
    }
    catch (\Exception $e) {
      watchdog_exception('byteplant_email_validation', $e);
      $content = [];
      $content = new \stdClass();
    }
    return $content;
  }
+18 −0
Original line number Diff line number Diff line
@@ -67,6 +67,23 @@ class EmailValidationForm extends ConfigFormBase {
      '#default_value' => $config->get('message'),
    ];

    $form['logging_group'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Loggin and Debug Options'),
      'logging' => [
        '#type' => 'checkboxes',
        '#title' => $this->t('Select events to log during the email validation process:'),
        '#options' => [
          'success' => $this->t('Successful validations'),
          'error' => $this->t('Validation errors'),
          'request' => $this->t('Validation request process (about to send, complete, incomplete, etc)'),
          'email_error' => $this->t('Send email to default site email address on validation failure'),
          'email_success' => $this->t('Send email to default site email address to on successful validation'),
        ],
        '#default_value' => $config->get('logging'),
      ],
    ];

    return parent::buildForm($form, $form_state);
  }

@@ -88,6 +105,7 @@ class EmailValidationForm extends ConfigFormBase {
      ->set('url', $form_state->getValue('url'))
      ->set('forms', $form_state->getValue('forms'))
      ->set('message', $form_state->getValue('message'))
      ->set('logging', $form_state->getValue('logging'))
      ->save();
  }