Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
PagerFantaQueryAdapter
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
3 / 3
4
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 getNbResults
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getSlice
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4/**
5 * SPDX-FileCopyrightText: 2020-2024 LibreCode coop and contributors
6 * SPDX-License-Identifier: AGPL-3.0-or-later
7 */
8
9namespace OCA\Libresign\Db;
10
11use Doctrine\DBAL\Query\QueryBuilder;
12use OCA\Libresign\Vendor\Pagerfanta\Adapter\AdapterInterface;
13use OCA\Libresign\Vendor\Pagerfanta\Exception\InvalidArgumentException;
14use OCP\DB\QueryBuilder\IQueryBuilder;
15
16/**
17 * Adapter which calculates pagination from a Doctrine DBAL QueryBuilder.
18 *
19 * @implements AdapterInterface<array<string, mixed>>
20 */
21class PagerFantaQueryAdapter implements AdapterInterface {
22    /**
23     * @throws InvalidArgumentException if a non-SELECT query is given
24     */
25    public function __construct(
26        private IQueryBuilder $queryBuilder,
27        private IQueryBuilder $countQueryBuilder,
28    ) {
29        if ($queryBuilder->getType() !== QueryBuilder::SELECT) {
30            // @codeCoverageIgnoreStart
31            throw new InvalidArgumentException('Only SELECT queries can be paginated.');
32            // @codeCoverageIgnoreEnd
33        }
34    }
35
36    #[\Override]
37    public function getNbResults(): int {
38        $total = $this->countQueryBuilder->executeQuery()->fetchOne();
39
40        return abs((int)$total);
41    }
42
43    /**
44     * @psalm-suppress MixedReturnStatement
45     *
46     * @return array<int, array<string, mixed>>
47     */
48    #[\Override]
49    public function getSlice(int $offset, int $length): iterable {
50        $qb = clone $this->queryBuilder;
51
52        return $qb->setMaxResults($length)
53            ->setFirstResult($offset)
54            ->executeQuery()
55            ->fetchAll();
56    }
57}