Created
January 27, 2019 21:21
-
-
Save piotrbrzezina/c09368f044c9e376a411e31ecf8dad06 to your computer and use it in GitHub Desktop.
Flashcard step 8 (Event system)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\EventSubscriber; | |
use ApiPlatform\Core\EventListener\EventPriorities; | |
use App\Entity\User; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; | |
use Symfony\Component\HttpKernel\KernelEvents; | |
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; | |
class UserSubscriber implements EventSubscriberInterface | |
{ | |
private $passwordEncoder; | |
public function __construct(UserPasswordEncoderInterface $passwordEncoder) | |
{ | |
$this->passwordEncoder = $passwordEncoder; | |
} | |
public static function getSubscribedEvents() | |
{ | |
return [ | |
KernelEvents::VIEW => ['encodePassword', EventPriorities::PRE_WRITE], | |
]; | |
} | |
public function encodePassword(GetResponseForControllerResultEvent $event) | |
{ | |
$user = $event->getControllerResult(); | |
if (!$user instanceof User || ($user instanceof User && $user->plainPassword === null)) { | |
return; | |
} | |
$user->password = $this->passwordEncoder->encodePassword($user, $user->plainPassword); | |
$user->eraseCredentials(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment