Repository URL to install this package:
|
Version:
6.2.10 ▾
|
<?php
namespace DigitalAscetic\BaseUserBundle\Service;
use DigitalAscetic\BaseUserBundle\Entity\AbstractBaseUser;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
class UserService implements UserManagerInterface
{
const SERVICE_NAME = 'digital_ascetic_base_user.service.user';
/** @var EntityManagerInterface */
private $em;
/** @var UserPasswordHasherInterface */
private $userPasswordHasher;
/** @var string */
private $class;
/** @var bool */
private $isUserEnabled;
/**
* UserService constructor.
* @param EntityManagerInterface $em
* @param UserPasswordHasherInterface $userPasswordHasher
* @param string $class
* @param bool $isUserEnabled
*/
public function __construct(
EntityManagerInterface $em,
UserPasswordHasherInterface $userPasswordHasher,
string $class,
bool $isUserEnabled
)
{
$this->em = $em;
$this->userPasswordHasher = $userPasswordHasher;
$this->class = $class;
$this->isUserEnabled = $isUserEnabled;
}
public function findUserBy(array $criteria): ?UserInterface
{
return $this->em->getRepository($this->class)->findOneBy($criteria);
}
public function findUserByEmail($email)
{
return $this->findUserBy(['email' => $email]);
}
public function findUserByUsername($username)
{
return $this->findUserBy(['username' => $username]);
}
public function findUser(string $usernameOrEmail): ?UserInterface
{
if (preg_match('/^.+\@\S+\.\S+$/', $usernameOrEmail)) {
$user = $this->findUserByEmail($usernameOrEmail);
if (null !== $user) {
return $user;
}
}
return $this->findUserByUsername($usernameOrEmail);
}
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newEncodedPassword): void
{
$user->setPassword($newEncodedPassword);
$this->em->persist($user);
$this->em->flush();
}
public function updatePassword(PasswordAuthenticatedUserInterface $user, string $plainPassword): void
{
$newPasswordEncoded = $this->userPasswordHasher->hashPassword($user, $plainPassword);
$user->setPassword($newPasswordEncoded);
}
public function updateUser(PasswordAuthenticatedUserInterface $user, $flush = true): void
{
/** AbstractBaseUser $user */
if ($this->isAbstractUser($user)) {
if (!empty($user->getPlainPassword())) {
$this->updatePassword($user, $user->getPlainPassword());
}
if (is_null($user->isEnabled())) {
$user->setEnabled($this->isUserEnabled);
}
$user->eraseCredentials();
}
$this->em->persist($user);
if ($flush) {
$this->em->flush();
}
}
private function isAbstractUser($entity)
{
return ($entity instanceof AbstractBaseUser);
}
}