summaryrefslogtreecommitdiff
path: root/QueryBuilderPaginator.php
blob: 02bed79fd912686cf1c2c6513b1e134f20e2f74a (plain)
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
<?php

declare(strict_types=1);

namespace Vendor\Extension\Helper;

use TYPO3\CMS\Core\Database\Query\QueryBuilder;
use TYPO3\CMS\Core\Pagination\AbstractPaginator;

/**
 * Copy of TYPO3\CMS\Extbase\Pagination\QueryResultPaginator
 * that supports a QueryBuilder as source
 */
class QueryBuilderPaginator extends AbstractPaginator
{
    private QueryBuilder $queryBuilder;

    private array $paginatedQueryResult;

    public function __construct(
        QueryBuilder $queryBuilder,
        int $currentPageNumber = 1,
        int $itemsPerPage = 10
    ) {
        $this->queryBuilder = $queryBuilder;
        $this->setCurrentPageNumber($currentPageNumber);
        $this->setItemsPerPage($itemsPerPage);

        $this->updateInternalState();
    }

    public function getPaginatedItems(): iterable
    {
        return $this->paginatedQueryResult;
    }

    protected function updatePaginatedItems(int $limit, int $offset): void
    {
        $this->paginatedQueryResult = $this->queryBuilder
            ->setMaxResults($limit)
            ->setFirstResult($offset)
            ->execute()
            ->fetchAllAssociative();
    }

    protected function getTotalAmountOfItems(): int
    {
        return (clone $this->queryBuilder)->count('uid')->executeQuery()->fetchOne();
    }

    protected function getAmountOfItemsOnCurrentPage(): int
    {
        return count($this->paginatedQueryResult);
    }
}