File size: 2,596 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 | <?php
declare(strict_types=1);
namespace User\Infrastructure\Services;
use Easy\Container\Attributes\Inject;
use Laminas\Diactoros\ServerRequestFactory;
use Option\Infrastructure\OptionResolver;
use Presentation\Resources\Api\UserResource;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Email;
use Twig\Environment;
use User\Domain\Entities\UserEntity;
class VerificationEmailService
{
public function __construct(
private MailerInterface $mailer,
private Environment $twig,
private OptionResolver $optionResolver,
#[Inject('option.mail.from.address')]
private ?string $fromAddress = null,
#[Inject('option.mail.from.name')]
private ?string $fromName = null,
#[Inject('option.site.email_verification_policy')]
private ?string $policy = null,
) {
}
public function send(UserEntity $user)
{
if (
!in_array($this->policy, ['strict', 'relaxed'])
|| $user->isEmailVerified()->value
) {
return;
}
try {
$email = new Email();
if ($this->fromAddress) {
$email->from(new Address(
$this->fromAddress,
$this->fromName ?: ''
));
}
// Create reset URL from the User ID and Recovery Token
$path = '/verification/email'
. '/' . (string) $user->getId()->getValue()
. '/' . $user->getEmailVerificationToken()->value;
$req = ServerRequestFactory::fromGlobals();
$uri = $req->getUri()
->withPath($path)
->withQuery('')
->withFragment('');
// Prepare data for the email template
$data = [
'user' => new UserResource($user),
'verification_url' => (string) $uri,
];
$data = array_merge($data, $this->optionResolver->getOptionMap());
// Set up the email
$email
->to($user->getEmail()->value)
->subject('Email verification required for your account')
->html($this->twig->render('@emails/verify-email.twig', $data));
// Send the email
$this->mailer->send($email);
} catch (TransportExceptionInterface $th) {
// Catch exception here to avoid breaking the application
}
}
}
|