Completed
Push — master ( 060764...f21b16 )
by
unknown
43s queued 31s
created

AbstractPaginator::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 7
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Doctrine\Orm;
15
16
use ApiPlatform\Core\DataProvider\PartialPaginatorInterface;
17
use ApiPlatform\Core\Exception\InvalidArgumentException;
18
use Doctrine\ORM\Query;
19
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
20
21
abstract class AbstractPaginator implements \IteratorAggregate, PartialPaginatorInterface
22
{
23
    protected $paginator;
24
    protected $iterator;
25
    protected $firstResult;
26
    protected $maxResults;
27
28
    /**
29
     * @throws InvalidArgumentException
30
     */
31
    public function __construct(DoctrinePaginator $paginator)
32
    {
33
        $query = $paginator->getQuery();
34
35
        if (null === ($firstResult = $query->getFirstResult()) || null === $maxResults = $query->getMaxResults()) {
36
            throw new InvalidArgumentException(sprintf('"%1$s::setFirstResult()" or/and "%1$s::setMaxResults()" was/were not applied to the query.', Query::class));
37
        }
38
39
        $this->paginator = $paginator;
40
        $this->firstResult = $firstResult;
41
        $this->maxResults = $maxResults;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function getCurrentPage(): float
48
    {
49
        return floor($this->firstResult / $this->maxResults) + 1.;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getItemsPerPage(): float
56
    {
57
        return (float) $this->maxResults;
58
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63
    public function getIterator(): \Traversable
64
    {
65
        return $this->iterator ?? $this->iterator = $this->paginator->getIterator();
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function count(): int
72
    {
73
        return iterator_count($this->getIterator());
74
    }
75
}
76