added event to send email to user (#5034)

This commit is contained in:
Kevin Papst
2024-08-28 14:04:36 +02:00
committed by GitHub
parent 9d933f62c0
commit a19426147a
4 changed files with 35 additions and 5 deletions

View File

@@ -14,7 +14,7 @@ use Symfony\Contracts\EventDispatcher\Event;
class EmailEvent extends Event
{
public function __construct(private Email $email)
public function __construct(private readonly Email $email)
{
}

View File

@@ -11,12 +11,17 @@ namespace App\Event;
use App\Entity\User;
use Symfony\Component\Mime\Email;
use Symfony\Contracts\EventDispatcher\Event;
class UserEmailEvent extends EmailEvent
class UserEmailEvent extends Event
{
public function __construct(private User $user, Email $email)
public function __construct(private readonly User $user, private readonly Email $email)
{
parent::__construct($email);
}
public function getEmail(): Email
{
return $this->email;
}
public function getUser(): User

View File

@@ -10,6 +10,7 @@
namespace App\EventSubscriber;
use App\Event\EmailEvent;
use App\Event\UserEmailEvent;
use App\Mail\KimaiMailer;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
@@ -26,6 +27,7 @@ final class EmailSubscriber implements EventSubscriberInterface
{
return [
EmailEvent::class => ['onMailEvent', 100],
UserEmailEvent::class => ['onUserMailEvent', 100],
];
}
@@ -33,4 +35,9 @@ final class EmailSubscriber implements EventSubscriberInterface
{
$this->mailer->send($event->getEmail());
}
public function onUserMailEvent(UserEmailEvent $event): void
{
$this->mailer->sendToUser($event->getUser(), $event->getEmail());
}
}

View File

@@ -10,6 +10,7 @@
namespace App\Mail;
use App\Configuration\MailConfiguration;
use App\Entity\User;
use Symfony\Component\Mailer\Envelope;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
@@ -23,10 +24,27 @@ final class KimaiMailer implements MailerInterface
public function send(RawMessage $message, Envelope $envelope = null): void
{
if ($message instanceof Email && \count($message->getFrom()) === 0) {
if (!$message instanceof Email) {
$email = new Email();
$email->text($message->toString());
$message = $email;
}
if (\count($message->getFrom()) === 0) {
$message->from($this->configuration->getFromAddress());
}
$this->mailer->send($message);
}
public function sendToUser(User $user, Email $message, Envelope $envelope = null): void
{
if (!$user->isEnabled() || $user->getEmail() === null) {
return;
}
$message->to($user->getEmail());
$this->send($message, $envelope);
}
}