選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

UserPasswordEventSubscriber.php 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace Lc\SovBundle\EventSubscriber\User;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Lc\SovBundle\Doctrine\EntityInterface;
  5. use Lc\SovBundle\Doctrine\Extension\SortableInterface;
  6. use Lc\SovBundle\Doctrine\Extension\StatusInterface;
  7. use Lc\SovBundle\Doctrine\Extension\TreeInterface;
  8. use Lc\SovBundle\Event\EntityManager\EntityManagerEvent;
  9. use Lc\SovBundle\Model\User\UserInterface;
  10. use Lc\SovBundle\Repository\AbstractRepositoryInterface;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
  13. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  14. class UserPasswordEventSubscriber implements EventSubscriberInterface
  15. {
  16. protected $passwordEncoder;
  17. public function __construct(UserPasswordEncoderInterface $passwordEncoder)
  18. {
  19. $this->passwordEncoder = $passwordEncoder;
  20. }
  21. public static function getSubscribedEvents()
  22. {
  23. return [
  24. EntityManagerEvent::PRE_CREATE_EVENT => ['setUserPasswordIfNull'],
  25. ];
  26. }
  27. public function setUserPasswordIfNull(EntityManagerEvent $event)
  28. {
  29. $entity = $event->getEntity();
  30. if ($entity instanceof UserInterface) {
  31. if ($entity->getPassword() == null) {
  32. $password = $this->passwordEncoder->encodePassword($entity, $entity->generatePassword());
  33. $entity->setPassword($password);
  34. }
  35. }
  36. }
  37. }