<?php
namespace AdminBundle\Repository;
use AdminBundle\Entity\User;
use DateTime;
class UserRepository extends BaseRepository
{
const BATCH_SIZE = 1000;
public function findEnabledByRoleQb(string $role)
{
$qb = $this->createQueryBuilder('u');
return $qb
->select('u.id, u.apiKey')
->where('u.enabled = :enabled')
->andWhere($qb->expr()->like('u.roles', ':role'))
->andWhere($qb->expr()->isNotNull('u.apiKey'))
->setParameter('enabled', true)
->setParameter('role', "%${role}%")
;
}
public function findEnabledByRole(string $role, int $firstResult = null, int $maxResults = null)
{
$qb = $this->findEnabledByRoleQb($role);
if ($firstResult) {
$qb->setFirstResult($firstResult);
}
if ($maxResults) {
$qb->setMaxResults($maxResults);
}
return $qb->getQuery()->getArrayResult();
}
public function findActiveByDateAndRole(string $role, bool $inactive = null)
{
$qb = $this->findEnabledByRoleQb($role);
if ($role === User::ROLE_CLIENT) {
return $qb
->andWhere($qb->expr()->isNotNull('u.lastLogin'))
->andWhere($qb->expr()->between('u.lastLogin', ':startDate', ':endDate'))
->setParameter('startDate', new DateTime('-30 days'))
->setParameter('endDate', new DateTime())
->getQuery()
->getArrayResult();
}
$qb->innerJoin('u.driver', 'd');
if ($inactive) {
return $qb
->andWhere($qb->expr()->lt('d.lastUpdatePozition', ':date'))
->setParameter('date', new DateTime('-7 days'))
->getQuery()
->getArrayResult()
;
}
return $qb
->andWhere($qb->expr()->between('d.lastUpdatePozition', ':startDate', ':endDate'))
->setParameter('startDate', new DateTime('-7 days'))
->setParameter('endDate', new DateTime())
->getQuery()
->getArrayResult()
;
}
public function findClientsHavingBookings(int $bookingsCount = 1)
{
$qb = $this->findEnabledByRoleQb(User::ROLE_CLIENT);
return $qb
->addSelect('COUNT(b.id) as bookingsCount')
->innerJoin('u.clientBookings', 'b')
->groupBy('u.id')
->having($qb->expr()->eq('bookingsCount', ':bookingsCount'))
->setParameter('bookingsCount', $bookingsCount)
->getQuery()
->getArrayResult()
;
}
/**
* Get the users without an apiKey QueryBuilder.
*
* @return QueryBuilder
*/
protected function usersNoApiKey() {
return $this->createQueryBuilder('u')->where("u.apiKey is NULL or u.apiKey = ''");
}
/**
* Get the total number of users without an apiKey.
*
* @return integer
*/
public function usersNoApiKeyCount() {
return $this->usersNoApiKey()->select('count(u.id)')->getQuery()->getSingleScalarResult();
}
/**
* Get the a batch of users without an apiKey.
*
* @return array
*/
public function usersNoApiKeyData() {
$qb = $this->usersNoApiKey()->select('u')->setMaxResults(self::BATCH_SIZE);
return $qb->getQuery()->getResult();
}
}