You are here

class UserMailQueueProcessor in Open Social 10.3.x

Same name and namespace in other branches
  1. 8.9 modules/social_features/social_user/src/Plugin/QueueWorker/UserMailQueueProcessor.php \Drupal\social_user\Plugin\QueueWorker\UserMailQueueProcessor
  2. 8.8 modules/social_features/social_user/src/Plugin/QueueWorker/UserMailQueueProcessor.php \Drupal\social_user\Plugin\QueueWorker\UserMailQueueProcessor
  3. 10.0.x modules/social_features/social_user/src/Plugin/QueueWorker/UserMailQueueProcessor.php \Drupal\social_user\Plugin\QueueWorker\UserMailQueueProcessor
  4. 10.1.x modules/social_features/social_user/src/Plugin/QueueWorker/UserMailQueueProcessor.php \Drupal\social_user\Plugin\QueueWorker\UserMailQueueProcessor
  5. 10.2.x modules/social_features/social_user/src/Plugin/QueueWorker/UserMailQueueProcessor.php \Drupal\social_user\Plugin\QueueWorker\UserMailQueueProcessor

Queue worker to process email to users.

Plugin annotation


@QueueWorker(
  id = "user_email_queue",
  title = @Translation("User email processor"),
  cron = {"time" = 60}
)

Hierarchy

Expanded class hierarchy of UserMailQueueProcessor

File

modules/social_features/social_user/src/Plugin/QueueWorker/UserMailQueueProcessor.php, line 28

Namespace

Drupal\social_user\Plugin\QueueWorker
View source
class UserMailQueueProcessor extends QueueWorkerBase implements ContainerFactoryPluginInterface {
  use LoggerChannelTrait;
  use StringTranslationTrait;

  /**
   * The mail manager.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * The entity storage.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $storage;

  /**
   * The database connection.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $connection;

  /**
   * The language manager interface.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The Email validator service.
   *
   * @var \Drupal\Component\Utility\EmailValidatorInterface
   */
  protected $emailValidator;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MailManagerInterface $mail_manager, EntityTypeManagerInterface $entity_type_manager, TranslationInterface $string_translation, Connection $database, LanguageManagerInterface $language_manager, EmailValidatorInterface $email_validator) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->mailManager = $mail_manager;
    $this->storage = $entity_type_manager;
    $this->connection = $database;
    $this
      ->setStringTranslation($string_translation);
    $this->languageManager = $language_manager;
    $this->emailValidator = $email_validator;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('plugin.manager.mail'), $container
      ->get('entity_type.manager'), $container
      ->get('string_translation'), $container
      ->get('database'), $container
      ->get('language_manager'), $container
      ->get('email.validator'));
  }

  /**
   * {@inheritdoc}
   */
  public function processItem($data) {

    // Validate if the queue data is complete before processing.
    if (self::validateQueueItem($data)) {

      // Get the email content that needs to be sent.

      /** @var \Drupal\social_queue_storage\Entity\QueueStorageEntity $queue_storage */
      $queue_storage = $this->storage
        ->getStorage('queue_storage_entity')
        ->load($data['mail']);

      // Check if it's from the configured email bundle type.
      if ($queue_storage
        ->bundle() === 'email') {

        // When there are user ID's configured.
        if ($data['users']) {

          // Load the users that are in the batch.
          $users = $this->storage
            ->getStorage('user')
            ->loadMultiple($data['users']);

          /** @var \Drupal\user\UserInterface $user */
          foreach ($users as $user) {

            // Attempt sending mail.
            if ($user
              ->getEmail()) {
              $this
                ->sendMail($user
                ->getEmail(), $user
                ->language()
                ->getId(), $queue_storage, $user
                ->getDisplayName());
            }
          }
        }

        // When there are email addresses configured.
        if ($data['user_mail_addresses']) {
          foreach ($data['user_mail_addresses'] as $mail_address) {
            if ($this->emailValidator
              ->isValid($mail_address['email_address'])) {

              // Attempt sending mail.
              $this
                ->sendMail($mail_address['email_address'], $this->languageManager
                ->getDefaultLanguage()
                ->getId(), $queue_storage, $mail_address['display_name']);
            }
          }
        }

        // Check if this is the last item.
        if ($this
          ->lastItem($data['mail'])) {
          $queue_storage
            ->setFinished(TRUE);

          // Try to save a the storage entity to update the finished status.
          try {

            // Saving the entity and setting it to finished should send
            // a message template.
            $queue_storage
              ->save();
          } catch (EntityStorageException $e) {
            $this
              ->getLogger('user_email_queue')
              ->error($e
              ->getMessage());
          }
        }
      }
    }
  }

  /**
   * Send the email.
   *
   * @param string $user_mail
   *   The recipient email address.
   * @param string $langcode
   *   The recipient language.
   * @param \Drupal\social_queue_storage\Entity\QueueStorageEntity $mail_params
   *   The email content from the storage entity.
   * @param string $display_name
   *   In case of anonymous users a display name will be given.
   */
  protected function sendMail(string $user_mail, string $langcode, QueueStorageEntity $mail_params, $display_name = NULL) {
    $context = [
      'subject' => $mail_params
        ->get('field_subject')->value,
      'message' => $mail_params
        ->get('field_message')->value,
    ];
    if ($display_name) {
      $context['display_name'] = $display_name;
    }

    // Attempt sending mail.
    $this->mailManager
      ->mail('system', 'action_send_email', $user_mail, $langcode, [
      'context' => $context,
    ], $mail_params
      ->get('field_reply_to')->value);
  }

  /**
   * Check if this item is last.
   *
   * @param string $mail_id
   *   The email ID that is in the batch.
   *
   * @return int
   *   The remaining number.
   */
  protected function lastItem($mail_id) {

    // Escape the condition values.
    $item_type = $this->connection
      ->escapeLike('mail');
    $item_id = $this->connection
      ->escapeLike($mail_id);

    // Get all queue items from the queue worker.
    $query = $this->connection
      ->select('queue', 'q');
    $query
      ->fields('q', [
      'data',
      'name',
    ]);

    // Plugin name is queue name.
    $query
      ->condition('q.name', 'user_email_queue');

    // Add conditions for the item type and item mail id's.
    // This is not exact but an educated guess as there can be user id's in the
    // data that could contain the item id.
    $query
      ->condition('q.data', '%' . $item_type . '%', 'LIKE');
    $query
      ->condition('q.data', '%' . $item_id . '%', 'LIKE');
    $results = (int) $query
      ->countQuery()
      ->execute()
      ->fetchField();

    // Return TRUE when last item.
    return !($results !== 1);
  }

  /**
   * Validate the queue item data.
   *
   * Before processing the queue item data we want to check if all the
   * necessary components are available.
   *
   * @param array $data
   *   The content of the queue item.
   *
   * @return bool
   *   True if the item contains all the necessary data.
   */
  private static function validateQueueItem(array $data) {

    // The queue data must contain the 'mail' key and it should either
    // contain 'users' or 'user_mail_addresses'.
    return isset($data['mail']) && (isset($data['users']) || isset($data['user_mail_addresses']));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UserMailQueueProcessor::$connection protected property The database connection.
UserMailQueueProcessor::$emailValidator protected property The Email validator service.
UserMailQueueProcessor::$languageManager protected property The language manager interface.
UserMailQueueProcessor::$mailManager protected property The mail manager.
UserMailQueueProcessor::$storage protected property The entity storage.
UserMailQueueProcessor::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
UserMailQueueProcessor::lastItem protected function Check if this item is last.
UserMailQueueProcessor::processItem public function Works on a single queue item. Overrides QueueWorkerInterface::processItem
UserMailQueueProcessor::sendMail protected function Send the email.
UserMailQueueProcessor::validateQueueItem private static function Validate the queue item data.
UserMailQueueProcessor::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct