93 lines
2.5 KiB
PHP

<?php
declare(strict_types=1);
/*
* Chill is a software for social workers
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Chill\MainBundle\Security\PasswordRecover;
use Chill\MainBundle\Entity\User;
use Chill\MainBundle\Notification\Mailer;
use DateTimeInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use function array_merge;
class RecoverPasswordHelper
{
public const RECOVER_PASSWORD_ROUTE = 'password_recover';
private MailerInterface $mailer;
/**
* @var TokenManager
*/
private $tokenManager;
/**
* @var UrlGeneratorInterface
*/
private $urlGenerator;
public function __construct(
TokenManager $tokenManager,
UrlGeneratorInterface $urlGenerator,
MailerInterface $mailer,
) {
$this->tokenManager = $tokenManager;
$this->urlGenerator = $urlGenerator;
$this->mailer = $mailer;
}
/**
* @param bool $absolute
* @param array $parameters additional parameters to url
*
* @return string
*/
public function generateUrl(User $user, DateTimeInterface $expiration, $absolute = true, array $parameters = [])
{
return $this->urlGenerator->generate(
self::RECOVER_PASSWORD_ROUTE,
array_merge(
$this->tokenManager->generate($user, $expiration),
$parameters
),
UrlGeneratorInterface::ABSOLUTE_URL
);
}
public function sendRecoverEmail(
User $user,
DateTimeInterface $expiration,
$template = '@ChillMain/Password/recover_email.txt.twig',
array $templateParameters = [],
$force = false,
array $additionalUrlParameters = [],
$emailSubject = 'Recover your password'
) {
if (null === $user->getEmail() || '' === trim($user->getEmail())) {
throw new \UnexpectedValueException("No emaail associated to the user");
}
$email = (new TemplatedEmail())
->subject($emailSubject)
->to($user->getEmail())
->textTemplate($template)
->context([
'user' => $user,
'url' => $this->generateUrl($user, $expiration, true, $additionalUrlParameters),
...$templateParameters
]);
$this->mailer->send($email);
}
}