added some exception handling
This commit is contained in:
parent
08ab8c3376
commit
d5b429da81
@ -4,7 +4,10 @@ namespace App\Repository;
|
||||
|
||||
use App\Entity\Quotes;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\DBAL\Query\QueryBuilder;
|
||||
use Doctrine\ORM\NonUniqueResultException;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
use Exception;
|
||||
|
||||
/**
|
||||
* @method Quotes|null find($id, $lockMode = null, $lockVersion = null)
|
||||
@ -21,7 +24,7 @@ class QuotesRepository extends ServiceEntityRepository
|
||||
|
||||
public function add(Quotes $entity, bool $flush = true): void
|
||||
{
|
||||
$this->_em->persist($entity);
|
||||
$this->_em->persist(entity: $entity);
|
||||
if ($flush) {
|
||||
$this->_em->flush();
|
||||
}
|
||||
@ -29,31 +32,40 @@ class QuotesRepository extends ServiceEntityRepository
|
||||
|
||||
public function remove(Quotes $entity, bool $flush = true): void
|
||||
{
|
||||
$this->_em->remove($entity);
|
||||
$this->_em->remove(entity: $entity);
|
||||
if ($flush) {
|
||||
$this->_em->flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return float|int|mixed|string|null
|
||||
*
|
||||
* @throws \Doctrine\ORM\NonUniqueResultException
|
||||
*/
|
||||
public function findOneRandom(): mixed
|
||||
public function findOneRandom(): ?QueryBuilder
|
||||
{
|
||||
$idLimits = $this->createQueryBuilder(alias: 'q')
|
||||
->select('MIN(q.id)', 'MAX(q.id)')
|
||||
->getQuery()
|
||||
->getOneOrNullResult();
|
||||
$randomPossibleId = random_int(min: $idLimits[1], max: $idLimits[2]);
|
||||
try {
|
||||
$idLimits = $this->createQueryBuilder(alias: 'q')
|
||||
->select('MIN(q.id)', 'MAX(q.id)')
|
||||
->getQuery()
|
||||
->getOneOrNullResult();
|
||||
} catch (NonUniqueResultException) {
|
||||
$idLimits = 0;
|
||||
}
|
||||
|
||||
return $this->createQueryBuilder(alias: 'q')
|
||||
->where(predicates: 'q.id >= :random_id')
|
||||
->setParameter(key: 'random_id', value: $randomPossibleId)
|
||||
->setMaxResults(maxResults: 1)
|
||||
->getQuery()
|
||||
->getOneOrNullResult();
|
||||
try {
|
||||
$randomPossibleId = random_int(min: $idLimits[1], max: $idLimits[2]);
|
||||
} catch(Exception) {
|
||||
$randomPossibleId = 0; // return first, if any
|
||||
}
|
||||
|
||||
try {
|
||||
return $this->createQueryBuilder(alias: 'q')
|
||||
->where(predicates: 'q.id >= :random_id')
|
||||
->setParameter(key: 'random_id', value: $randomPossibleId)
|
||||
->setMaxResults(maxResults: 1)
|
||||
->getQuery()
|
||||
->getOneOrNullResult();
|
||||
} catch (NonUniqueResultException) {
|
||||
// max results is 1
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
|
Loading…
Reference in New Issue
Block a user