<?php
namespace App\EventListener;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Manager\CustomerManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class ForgotPasswordRequestSubscriber.
*/
final class ForgotPasswordRequestSubscriber implements EventSubscriberInterface
{
/**
* @var CustomerManager
*/
private $manager;
/**
* ForgotPasswordRequestSubscriber constructor.
*
* @param CustomerManager $manager
*/
public function __construct(CustomerManager $manager)
{
$this->manager = $manager;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::VIEW => ['sendPasswordResetUrl', EventPriorities::POST_VALIDATE],
];
}
/**
* @param GetResponseForControllerResultEvent $event
*
* @throws \Twig_Error_Loader
* @throws \Twig_Error_Runtime
* @throws \Twig_Error_Syntax
*/
public function sendPasswordResetUrl(GetResponseForControllerResultEvent $event)
{
$request = $event->getRequest();
if ('api_forgot_password_requests_post_collection' !== $request->attributes->get('_route')) {
return;
}
$forgotPasswordRequest = $event->getControllerResult();
$user = $this->manager->findOneByEmail($forgotPasswordRequest->email);
if (!$user) {
throw new NotFoundHttpException("No user found with email $forgotPasswordRequest->email");
}
$this->manager->requestPasswordReset($user);
$event->setResponse(new JsonResponse(null, 204));
}
}