-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueryBuilderAdapter.php
57 lines (47 loc) · 1.24 KB
/
QueryBuilderAdapter.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
50
51
52
53
54
55
56
57
<?php
declare(strict_types=1);
namespace SonsOfPHP\Bridge\Doctrine\DBAL\Pager;
use Doctrine\DBAL\Query\QueryBuilder;
use SonsOfPHP\Contract\Pager\AdapterInterface;
/**
* Usage:
* $adapter = new QueryBuilderAdapter($queryBuilder, function (QueryBuilder $builder): void {
* $builder->select('COUNT(DISTINCT e.id) AS cnt');
* });
*
* @author Joshua Estes <[email protected]>
*/
class QueryBuilderAdapter implements AdapterInterface
{
private $countQuery;
public function __construct(
private readonly QueryBuilder $builder,
callable $countQuery,
) {
$this->countQuery = $countQuery;
}
/**
* {@inheritdoc}
*/
public function count(): int
{
$builder = clone $this->builder;
$callable = $this->countQuery;
$callable($builder);
$builder->setMaxResults(1);
return (int) $builder->executeQuery()->fetchOne();
}
/**
* {@inheritdoc}
*/
public function getSlice(int $offset, ?int $length): iterable
{
$builder = clone $this->builder;
return $builder
->setFirstResult($offset)
->setMaxResults($length)
->executeQuery()
->fetchAllAssociative()
;
}
}