death-notifier/src/main/php/com/fwdekker/deathnotifier/mailer/Email.php

77 lines
2.6 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier\mailer;
use Exception;
/**
* A serializable email that can be queued in a database and can be sent.
*
* When serialized, an email is represented by the type of email and two arguments. When deserialized, an email can be
* constructed from those arguments, and the implementation returns a specific subject and message.
*/
abstract class Email
{
/**
* @var string A string identifying the type of email.
*/
public string $type;
/**
* @var string The intended recipient of the email.
*/
public string $recipient;
/**
* @var string The first argument to construct the email.
*/
public string $arg1 = "";
/**
* @var string The second argument to construct the email.
*/
public string $arg2 = "";
/**
* Returns the subject header of the email.
*
* @return string the subject header of the email
*/
public abstract function getSubject(): string;
/**
* Returns the body of the email.
*
* @param array<string, array<string, mixed>> $config the software configuration
* @return string the body of the email
*/
public abstract function getBody(array $config): string;
/**
* Deserializes an email back into an instance.
*
* Only types of emails that are known can be deserialized.
*
* @param string $type the type of email to deserialize
* @param string $recipient the intended recipient of the email
* @param string $arg1 the first argument to construct the email
* @param string $arg2 the second argument to construct the email
* @return Email a deserialized email
* @throws Exception if the `type` is not recognized
*/
public static function deserialize(string $type, string $recipient, string $arg1, string $arg2): Email
{
return match ($type) {
RegisterEmail::TYPE => new RegisterEmail($recipient, $arg1),
VerifyEmailEmail::TYPE => new VerifyEmailEmail($recipient, $arg1),
ChangedEmailEmail::TYPE => new ChangedEmailEmail($recipient, $arg1),
ChangedPasswordEmail::TYPE => new ChangedPasswordEmail($recipient),
ResetPasswordEmail::TYPE => new ResetPasswordEmail($recipient, $arg1),
NotifyArticleDeletedEmail::TYPE => new NotifyArticleDeletedEmail($recipient, $arg1),
NotifyArticleUndeletedEmail::TYPE => new NotifyArticleUndeletedEmail($recipient, $arg1),
NotifyStatusChangedEmail::TYPE => new NotifyStatusChangedEmail($recipient, $arg1, $arg2),
default => throw new Exception("Unknown email type $type."),
};
}
}