aboutsummaryrefslogtreecommitdiff
path: root/lib/classes/JsonApi/JsonApiIntegration/Paginator.php
blob: 7e74f8066000a20c0771f7860d412e7d6cfb98b2 (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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php

namespace JsonApi\JsonApiIntegration;

/**
 * Diese Klasse bündelt lediglich die Logik, um aus dem Triple [Gesamtanzahl,
 * Offset, Limit], die neuen Triple für die nächste, vorherige, erste
 * oder letzte Seite zu generieren.
 *
 * @internal
 */
class Paginator
{
    /** @var int|null */
    private $total;

    /** @var int */
    private $offset;

    /** @var int */
    private $limit;

    /**
     * @param int|null $total
     * @param int      $offset
     * @param int      $limit
     */
    public function __construct($total, $offset, $limit)
    {
        $this->total = $total;
        $this->offset = $offset;
        $this->limit = $limit;
    }

    public function getFirstPageOffsetAndLimit(): array
    {
        if (0 === $this->limit) {
            return [0, 0];
        }

        return [0, $this->limit];
    }

    public function getLastPageOffsetAndLimit(): ?array
    {
        if (!isset($this->total)) {
            return null;
        }

        if ($this->limit === 0) {
            return [0, 0];
        }

        $last = max(0, floor($this->total / $this->limit - 1) * $this->limit);

        return [$last, $this->limit];
    }

    public function getPrevPageOffsetAndLimit(): ?array
    {
        if ($this->limit === 0) {
            return null;
        }

        if ($this->offset - $this->limit < 0) {
            return null;
        }

        return [max(0, $this->offset - $this->limit), $this->limit];
    }

    public function getNextPageOffsetAndLimit(): ?array
    {
        if ($this->limit === 0) {
            return null;
        }

        if (isset($this->total) && $this->total <= $this->offset + $this->limit) {
            return null;
        }

        return [$this->offset + $this->limit, $this->limit];
    }
}