-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseRepository.php
49 lines (36 loc) · 1.09 KB
/
BaseRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
namespace App\Repository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
abstract class BaseRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry, $entityClass) {
parent::__construct($registry, $entityClass);
}
public function findInRandomOrder(int $number = 1)
{
$ids = $this->randomIds($number);
return $this->findBy(['id' => $ids]);
}
public function randomIds(int $number)
{
$elements = $this->createQueryBuilder('e')
->addSelect('e.id')
->getQuery()
->getArrayResult();
$ids = [];
foreach ($elements as $element) {
$ids[] = $element[0]['id'];
}
if (empty($ids)) {
return [];
}
$number = count($ids) > $number ? $number : count($ids);
$keys = array_rand($ids, $number);
$results = [];
foreach ($keys as $key) {
$results[] = $ids[$key];
}
return $results;
}
}