Skip to content

Instantly share code, notes, and snippets.

@piotrbrzezina
Created January 27, 2019 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotrbrzezina/c09368f044c9e376a411e31ecf8dad06 to your computer and use it in GitHub Desktop.
Save piotrbrzezina/c09368f044c9e376a411e31ecf8dad06 to your computer and use it in GitHub Desktop.
Flashcard step 8 (Event system)
<?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