Passed
Push — master ( e2a719...9eb666 )
by Alan
03:22
created

ArrayPaginator::getTotalItems()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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\DataProvider;
15
16
/**
17
 * Paginator for arrays.
18
 *
19
 * @author Alan Poulain <[email protected]>
20
 */
21
final class ArrayPaginator implements \IteratorAggregate, PaginatorInterface
22
{
23
    private $iterator;
24
    private $firstResult;
25
    private $maxResults;
26
    private $totalItems;
27
28
    public function __construct(array $results, int $firstResult, int $maxResults)
29
    {
30
        if ($maxResults > 0) {
31
            $this->iterator = new \LimitIterator(new \ArrayIterator($results), $firstResult, $maxResults);
32
        } else {
33
            $this->iterator = new \EmptyIterator();
34
        }
35
        $this->firstResult = $firstResult;
36
        $this->maxResults = $maxResults;
37
        $this->totalItems = \count($results);
38
    }
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function getCurrentPage(): float
44
    {
45
        if (0 >= $this->maxResults) {
46
            return 1.;
47
        }
48
49
        return floor($this->firstResult / $this->maxResults) + 1.;
50
    }
51
52
    /**
53
     * {@inheritdoc}
54
     */
55
    public function getLastPage(): float
56
    {
57
        if (0 >= $this->maxResults) {
58
            return 1.;
59
        }
60
61
        return ceil($this->totalItems / $this->maxResults) ?: 1.;
62
    }
63
64
    /**
65
     * {@inheritdoc}
66
     */
67
    public function getItemsPerPage(): float
68
    {
69
        return (float) $this->maxResults;
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function getTotalItems(): float
76
    {
77
        return (float) $this->totalItems;
78
    }
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    public function count(): int
84
    {
85
        return iterator_count($this->iterator);
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function getIterator(): \Traversable
92
    {
93
        return $this->iterator;
94
    }
95
}
96