ldc-legaulois/app/Http/Controllers/Bo/MailTesterController.php
2026-09-23 15:11:48 +02:00

104 lines
3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http\Controllers\Bo;
use App\Enums\MailToTest;
use App\Http\Controllers\Controller;
use App\Http\Requests\Bo\SendTestMailRequest;
use App\Models\User;
use App\Notifications\Customer\VerifyEmail;
use Illuminate\Contracts\View\View;
use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Illuminate\Notifications\Notifiable;
use Illuminate\Notifications\Notification as BaseNotification;
class MailTesterController extends Controller
{
public function __construct()
{
$this->middleware('can:testMails,' . User::class);
}
public function listMails(): View
{
return view('bo.mail-testing');
}
public function sendMail(SendTestMailRequest $request): RedirectResponse
{
$recipient = $request->getToAddress();
$notifiable = $this->generateDummyNotifiable($recipient);
$mailableOrNotification = $this->getMailToSend(
$request->getMailToTest(),
$recipient,
);
if ($this->sendMailToRecipient($mailableOrNotification, $notifiable)) {
return back()->with('success', __("Le mail à été envoyé à l'adresse {$recipient->address}"));
}
return back()->with('error', 'Échec lors de l\'envoi du mail');
}
private function sendMailToRecipient(Mailable | BaseNotification $mail, mixed $dummyNotifiable): bool
{
/** @mixin \Illuminate\Notifications\Notifiable $dummyNotifiable */
if ($mail instanceof Mailable) {
return Mail::to($dummyNotifiable->address)->send($mail) !== null;
}
$dummyNotifiable->notifyNow($mail);
return true;
}
private function getMailToSend(MailToTest $mailToTest, Address $sendTo): Mailable | BaseNotification
{
return match ($mailToTest) {
MailToTest::ValidateAccount => $this->fromValidateAccountNotification(),
MailToTest::ForgottenPassword => null,
MailToTest::UpdatePassword => null,
MailToTest::OrderRecap => null,
};
}
private function generateDummyNotifiable(Address $sendTo): mixed
{
return new readonly class($sendTo, 'Nom et Prénom customer') {
use Notifiable;
public function __construct(
public Address $address,
public string $username,
) {}
public function getKey(): int
{
return 1;
}
public function getEmailForVerification(): string
{
return $this->address->address;
}
public function routeNotificationForMail(): string
{
return $this->address->address;
}
};
}
private function fromValidateAccountNotification(): BaseNotification
{
return new VerifyEmail();
}
}