38 lines
1.4 KiB
PHP
38 lines
1.4 KiB
PHP
<?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, string $module): void {
|
|
$mailManager = \Drupal::service('plugin.manager.mail');
|
|
$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;
|
|
}
|
|
}
|
|
|
|
|