* * @method User|null find( $id, $lockMode = null, $lockVersion = null ) * @method User|null findOneBy( array $criteria, array $orderBy = null ) * @method User[] findAll() * @method User[] findBy( array $criteria, array $orderBy = null, $limit = null, $offset = null ) */ class UserRepository extends ServiceEntityRepository implements PasswordUpgraderInterface { private ApiTokenRepository $apiTokenRepository; public function __construct( ManagerRegistry $registry, ApiTokenRepository $apiTokenRepository ) { parent::__construct( $registry, User::class ); $this->apiTokenRepository = $apiTokenRepository; } public function remove( User $entity, bool $flush = false ): void { $this->getEntityManager()->remove( $entity ); if ( $flush ) { $this->getEntityManager()->flush(); } } /** * Used to upgrade (rehash) the user's password automatically over time. */ public function upgradePassword( PasswordAuthenticatedUserInterface $user, string $newHashedPassword ): void { if ( ! $user instanceof User ) { throw new UnsupportedUserException( sprintf( 'Instances of "%s" are not supported.', get_class( $user ) ) ); } $user->setPassword( $newHashedPassword ); $this->save( $user, true ); } public function save( User $entity, bool $flush = false ): void { $this->getEntityManager()->persist( $entity ); if ( $flush ) { $this->getEntityManager()->flush(); } } public function findByApiToken( string $apiToken ): ?User { return $this->apiTokenRepository->findOneBy( [ 'token' => $apiToken ] )?->getUser(); } public function findByRole( string $role ): array { if ( ! preg_match( '/^ROLE_[A-Z]+$/', $role ) ) { throw new \InvalidArgumentException( 'Invalid role.' ); } return $this->createQueryBuilder( 'u' ) ->andWhere( 'u.roles LIKE :role' ) ->setParameter( 'role', '%"'.$role.'"%') ->getQuery() ->getResult(); } // /** // * @return User[] Returns an array of User objects // */ // public function findByExampleField($value): array // { // return $this->createQueryBuilder('u') // ->andWhere('u.exampleField = :val') // ->setParameter('val', $value) // ->orderBy('u.id', 'ASC') // ->setMaxResults(10) // ->getQuery() // ->getResult() // ; // } // public function findOneBySomeField($value): ?User // { // return $this->createQueryBuilder('u') // ->andWhere('u.exampleField = :val') // ->setParameter('val', $value) // ->getQuery() // ->getOneOrNullResult() // ; // } }