Added email alerter class
This commit is contained in:
parent
4ee9cd5bef
commit
18f8e6cab8
38
src/EmailAlerter.php
Normal file
38
src/EmailAlerter.php
Normal file
@ -0,0 +1,38 @@
|
||||
<?php declare(strict_types = 1);
|
||||
|
||||
namespace Drupal\opencase;
|
||||
use Drupal\user\Entity\User;
|
||||
|
||||
class EmailAlerter {
|
||||
public function send_email_to_users_with_role(array $params, string $key, string $role): void {
|
||||
$mailManager = \Drupal::service('plugin.manager.mail');
|
||||
$module = 'goodnightout_opencase';
|
||||
$to = implode(',', $this->get_email_addresses_of_users_with_role($role));
|
||||
$send = true;
|
||||
$result = $mailManager->mail($module, $key, $to, NULL, $params, NULL, $send);
|
||||
if ($result['result'] != true) {
|
||||
$message = t('There was a problem sending your email notification to @email.', array('@email' => $to));
|
||||
\Drupal::messenger()->addMessage($message, 'error');
|
||||
\Drupal::logger('mail-log')->error($message);
|
||||
return;
|
||||
}
|
||||
$message = t('An email notification has been sent to @email ', array('@email' => $to));
|
||||
\Drupal::messenger()->addMessage($message);
|
||||
\Drupal::logger('mail-log')->notice($message);
|
||||
}
|
||||
|
||||
private function get_email_addresses_of_users_with_role(string $role): array {
|
||||
$email_addresses = [];
|
||||
$ids = \Drupal::entityQuery('user')
|
||||
->condition('status', 1)
|
||||
->condition('roles', $role)
|
||||
->execute();
|
||||
$users = User::loadMultiple($ids);
|
||||
foreach($users as $user){
|
||||
$email_addresses[] = $user->getEmail();
|
||||
}
|
||||
return $email_addresses;
|
||||
}
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user