Fixed static analysis issue and added test for UserRepository

This commit is contained in:
Jan Böhmer 2023-08-01 16:20:31 +02:00
parent c981476706
commit b3153dac68
5 changed files with 117 additions and 3 deletions

View file

@ -170,7 +170,7 @@ class SecurityController extends AbstractController
$this->addFlash('success', 'pw_reset.new_pw.success');
$repo = $em->getRepository(User::class);
$u = $repo->findOneBy(['name' => $data['username']]);
$u = $repo->findByUsername($data['username']);
$event = new SecurityEvent($u);
/** @var EventDispatcher $eventDispatcher */
$eventDispatcher->dispatch($event, SecurityEvents::PASSWORD_RESET);

View file

@ -54,6 +54,7 @@ class UserFixtures extends Fixture implements DependentFixtureInterface
$user = new User();
$user->setName('user');
$user->setNeedPwChange(false);
$user->setEmail('user@invalid.invalid');
$user->setFirstName('Test')->setLastName('User');
$user->setPassword($this->encoder->hashPassword($user, 'test'));
$user->setGroup($this->getReference(GroupFixtures::USERS));
@ -66,6 +67,9 @@ class UserFixtures extends Fixture implements DependentFixtureInterface
$manager->persist($noread);
$manager->flush();
//Ensure that the anonymous user has the ID 0
$manager->getRepository(User::class)->changeID($anonymous, User::ID_ANONYMOUS);
}
public function getDependencies(): array

View file

@ -42,6 +42,7 @@ final class UserRepository extends NamedDBElementRepository implements PasswordU
/**
* Returns the anonymous user.
* The result is cached, so the database is only called once, after the anonymous user was found.
* @return User|null The user if it is existing, null if no one matched the criteria
*/
public function getAnonymousUser(): ?User
{
@ -54,6 +55,30 @@ final class UserRepository extends NamedDBElementRepository implements PasswordU
return $this->anonymous_user;
}
/**
* Find a user by its username.
* @param string $username
* @return User|null
*/
public function findByUsername(string $username): ?User
{
if ($username === '') {
return null;
}
$qb = $this->createQueryBuilder('u');
$qb->select('u')
->where('u.name = (:name)');
$qb->setParameter('name', $username);
try {
return $qb->getQuery()->getOneOrNullResult();
} catch (NonUniqueResultException) {
return null;
}
}
/**
* Find a user by its name or its email. Useful for login or password reset purposes.
*

View file

@ -97,8 +97,7 @@ class PasswordResetManager
{
//Try to find the user
$repo = $this->em->getRepository(User::class);
/** @var User|null $user */
$user = $repo->findOneBy(['name' => $username]);
$user = $repo->findByUsername($username);
//If no user matching the name, show an error message
if (!$user instanceof User) {