Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

47 lines
1.5KB

  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. }