namespace Wallabag\CoreBundle\Repository;
use Doctrine\ORM\EntityRepository;
+use Doctrine\ORM\NoResultException;
use Doctrine\ORM\QueryBuilder;
use Pagerfanta\Adapter\DoctrineORMAdapter;
use Pagerfanta\Pagerfanta;
* Find an entry by its url and its owner.
* If it exists, return the entry otherwise return false.
*
- * @param $url
- * @param $userId
+ * @param string $url
+ * @param int $userId
*
* @return Entry|bool
*/
/**
* Find all entries by url and owner.
*
- * @param $url
- * @param $userId
+ * @param string $url
+ * @param int $userId
*
* @return array
*/
/**
* Returns a random entry, filtering by status.
*
- * @param $userId
- * @param string $status can be unread, archive or starred
+ * @param int $userId
+ * @param string $type Can be unread, archive, starred, etc
*
- * @throws \Doctrine\ORM\NoResultException
- * @throws \Doctrine\ORM\NonUniqueResultException
+ * @throws NoResultException
*
* @return Entry
*/
- public function getRandomEntry($userId, $status = '')
+ public function getRandomEntry($userId, $type = '')
{
- $max = $this->getEntityManager()
- ->createQuery('SELECT MAX(e.id) FROM Wallabag\CoreBundle\Entity\Entry e WHERE e.user = :userId')
- ->setParameter('userId', $userId)
- ->getSingleScalarResult();
-
- $qb = $this->createQueryBuilder('e')
- ->where('e.user = :user_id')->setParameter('user_id', $userId);
+ $qb = $this->getQueryBuilderByUser($userId)
+ ->select('e.id');
- if ('unread' === $status) {
- $qb->andWhere('e.isArchived = false');
+ switch ($type) {
+ case 'unread':
+ $qb->andWhere('e.isArchived = false');
+ break;
+ case 'archive':
+ $qb->andWhere('e.isArchived = true');
+ break;
+ case 'starred':
+ $qb->andWhere('e.isStarred = true');
+ break;
+ case 'untagged':
+ $qb->leftJoin('e.tags', 't');
+ $qb->andWhere('t.id is null');
+ break;
}
- if ('archive' === $status) {
- $qb->andWhere('e.isArchived = true');
- }
+ $ids = $qb->getQuery()->getArrayResult();
- if ('starred' === $status) {
- $qb->andWhere('e.isStarred = true');
+ if (empty($ids)) {
+ throw new NoResultException();
}
- if ('untagged' === $status) {
- $qb->leftJoin('e.tags', 't');
- $qb->andWhere('t.id is null');
- }
+ // random select one in the list
+ $randomId = $ids[mt_rand(0, \count($ids) - 1)]['id'];
- return $qb->andWhere('e.id >= :rand')
- ->setParameter('rand', rand(0, $max))
- ->setMaxResults(1)
- ->getQuery()
- ->getSingleResult();
+ return $this->find($randomId);
}
/**