src/EventSubscriber/PasswordEncoder.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use ApiPlatform\Core\EventListener\EventPriorities;
  4. use App\Entity\User;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\ViewEvent;
  8. use Symfony\Component\HttpKernel\Exception\HttpException;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  11. class PasswordEncoder implements EventSubscriberInterface
  12. {
  13.     private $encoder;
  14.     public function __construct(UserPasswordEncoderInterface $encoder)
  15.     {
  16.         $this->encoder $encoder;
  17.     }
  18.     public static function getSubscribedEvents()
  19.     {
  20.         return [KernelEvents::VIEW => ['encodePassword'EventPriorities::PRE_WRITE]
  21.         ];
  22.     }
  23.     public function encodePassword(ViewEvent $event): void
  24.     {
  25.         $user $event->getControllerResult();
  26.         $method $event->getRequest()->getMethod();
  27.         if (!$user instanceof User && (Request::METHOD_POST !== $method || Request::METHOD_PUT!==$method)) {
  28.             return;
  29.         }
  30.         if(Request::METHOD_POST === $method){
  31.             $passHash $this->encoder->encodePassword($user$user->getPassword());
  32.             $user->setPassword($passHash);
  33.         }
  34.         if(Request::METHOD_PUT === $method){
  35.             if($user->getNewPassword()===null ||$user->getConfirmPassword() === null){
  36.                 return;
  37.             }
  38.             $check $this->encoder->isPasswordValid($user,$user->getConfirmPassword());
  39.             if ($check){
  40.                 $pass $this->encoder->encodePassword($user,$user->getNewPassword());
  41.                 $user->setPassword($pass);
  42.                 //dd($user);
  43.             }else{
  44.                 throw new HttpException(422"Password error");
  45.             }
  46.         }
  47.     }
  48. }