aboutsummaryrefslogtreecommitdiffhomepage
path: root/Digitigrade/Pagination.php
blob: 75a876fa39215e3ed2f09e3919ee849a58d84b8b (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
<?php
namespace Digitigrade;

use JsonMapper;

class Pagination {
    public int $page;
    public int $totalPages;
    public int $totalItems;
    public ?string $nextPage = null;
    public ?string $previousPage = null;
    public array $items;

    /**
     * Fetches a pagination page.
     * @param string $uri
     * @param class-string $innerType Type of the contained items.
     * @return self
     */
    public static function fromUri(string $uri): self {
        $response = send_request_authenticated($uri);
        $data = json_decode($response->body);
        if (!isset($data->page)) {
            throw new \RuntimeException("doesn't look like a pagination: $uri");
        }
        $p = (new JsonMapper())->map($data, self::class);
        return $p;
    }

    private function become(self $other) {
        $this->page = $other->page;
        $this->totalPages = $other->totalPages;
        $this->totalItems = $other->totalItems;
        $this->nextPage = $other->nextPage;
        $this->previousPage = $other->previousPage;
        $this->items = &$other->items;
    }

    /**
     * Gets the next item from the pagination, going to the next page if needed.
     * 
     * Careful! This behaves differently from PHP's built in `next`: it returns
     * the first item, the first time it's called, rather than the second.
     * @return mixed The next item, or `false` if at the end.
     */
    public function next(): mixed {
        if (current($this->items) === false) {
            if (isset($this->nextPage)) {
                $this->become(self::fromUri($this->nextPage));
                return $this->next();
            } else {
                return false;
            }
        } else {
            $item = current($this->items);
            next($this->items);
            return $item;
        }
    }
}