<?php
namespace App\EventSubscriber;
use ApiPlatform\Core\EventListener\EventPriorities;
use App\Entity\User;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\ViewEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class PasswordEncoder implements EventSubscriberInterface
{
private $encoder;
public function __construct(UserPasswordEncoderInterface $encoder)
{
$this->encoder = $encoder;
}
public static function getSubscribedEvents()
{
return [KernelEvents::VIEW => ['encodePassword', EventPriorities::PRE_WRITE]
];
}
public function encodePassword(ViewEvent $event): void
{
$user = $event->getControllerResult();
$method = $event->getRequest()->getMethod();
if (!$user instanceof User && (Request::METHOD_POST !== $method || Request::METHOD_PUT!==$method)) {
return;
}
if(Request::METHOD_POST === $method){
$passHash = $this->encoder->encodePassword($user, $user->getPassword());
$user->setPassword($passHash);
}
if(Request::METHOD_PUT === $method){
if($user->getNewPassword()===null ||$user->getConfirmPassword() === null){
return;
}
$check = $this->encoder->isPasswordValid($user,$user->getConfirmPassword());
if ($check){
$pass = $this->encoder->encodePassword($user,$user->getNewPassword());
$user->setPassword($pass);
//dd($user);
}else{
throw new HttpException(422, "Password error");
}
}
}
}