|
- <?php
-
- namespace App\Logic;
-
- use App\Events\Email\ConfirmEvent;
- use App\Exceptions\AppCommonException;
- use App\Email\BaseEmailer;
- use App\Models\Email;
- use App\Models\EmailAttachment;
- use Exception;
- use Illuminate\Database\Eloquent\Collection;
- use Illuminate\Support\Carbon;
- use Validator;
-
- class EmailManager
- {
-
- private Email $model;
-
- private bool $canSend = false;
-
- /**
- * @var Collection<int, EmailAttachment>|null
- */
- private ?Collection $attachments = null;
-
- public function __construct(int|BaseEmailer $param)
- {
- if (is_numeric($param)) {
- $this->model = Email::lockForUpdate()->findOrfail($param);
- $this->canSend = $this->model->send_datetime === null;
- if (!$this->checkAuth()) throw new AppCommonException("メール権限エラー");
- } else if ($param instanceof BaseEmailer) {
- $this->model = $param->makeModel();
- }
- }
-
- public function checkAuth()
- {
- return true;
- }
-
- public function getEmailId()
- {
- $this->model->setId();
- return $this->model->id;
- }
-
- public function getTimestamp(): Carbon|null
- {
- return $this->model->updated_at;
- }
-
- public function create()
- {
- $this->model->save();
- return [];
- }
-
- public function setSubject(string $subject)
- {
- if ($this->canSend()) {
- $this->model->subject = $subject;
- } else {
- throw new AppCommonException("送信済みメール編集エラー");
- }
- return $this;
- }
-
- public function setContent(string $content)
- {
-
- if ($this->canSend()) {
- $this->model->content = $content;
- } else {
- throw new AppCommonException("送信済みメール編集エラー");
- }
- return $this;
- }
-
- public function attach(string $filepath, string $filename, string $mimeType)
- {
-
- if ($this->attachments === null) {
- $this->attachments = new Collection();
- }
- $attachment = new EmailAttachment();
- $attachment->filepath = $filepath;
- $attachment->send_filename = $filename;
- $attachment->mime = $mimeType;
-
- $this->attachments->push($attachment);
-
- return $this;
- }
-
- public function update()
- {
- $this->model->save();
- return [];
- }
-
- public function confirm()
- {
-
- $validator = Validator::make(['email' => $this->model->email], [
- 'email' => ['required', 'email:strict,dns']
- ]);
-
- if ($validator->fails()) {
- throw new Exception(sprintf("%s [%s]", $validator->errors()->first(), $this->model->email));
- }
-
- if ($this->canSend() !== null) {
- $this->model->setId();
- ConfirmEvent::dispatch($this->model, $this->attachments);
- } else {
- throw new AppCommonException("送信済みエラー");
- }
- }
-
- public function canSend()
- {
- return $this->canSend;
- }
- }
|