Passed
Branch feature/first-release (57b0a8)
by Andrea Marco
13:40
created

ItemsPerPageHandler::matches()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 9.6111
cc 5
nc 7
nop 0
1
<?php
2
3
namespace Cerbero\LazyJsonPages\Handlers;
4
5
use Cerbero\LazyJsonPages\Concerns\HandlesTotalPages;
6
use GuzzleHttp\Psr7\Uri;
7
use Traversable;
8
9
/**
10
 * The items per page handler.
11
 *
12
 */
13
class ItemsPerPageHandler extends AbstractHandler
14
{
15
    use HandlesTotalPages;
0 ignored issues
show
introduced by
The trait Cerbero\LazyJsonPages\Concerns\HandlesTotalPages requires some properties which are not provided by Cerbero\LazyJsonPages\Handlers\ItemsPerPageHandler: $chunk, $source, $request, $path, $firstPage, $concurrency, $pageName, $timeout
Loading history...
16
17
    /**
18
     * Determine whether the handler can handle the APIs configuration
19
     *
20
     * @return bool
21
     */
22
    public function matches(): bool
23
    {
24
        return $this->config->perPageQuery
25
            && $this->config->nextPageKey === null
26
            && ($this->config->items || $this->config->pages || $this->config->lastPage);
27
    }
28
29
    /**
30
     * Handle the APIs configuration
31
     *
32
     * @return Traversable
33
     */
34
    public function handle(): Traversable
35
    {
36
        $originalUri = $this->config->source->request->getUri();
37
        $pages = (int) ceil($this->countItems() / $this->config->perPageOverride);
38
        $uri = Uri::withQueryValue($originalUri, $this->config->perPageQuery, $this->config->perPageOverride);
39
40
        yield from $this->handleByTotalPages($pages, $uri);
41
    }
42
43
    /**
44
     * Retrieve the total number of items
45
     *
46
     * @return int
47
     */
48
    protected function countItems(): int
49
    {
50
        if ($this->config->items) {
51
            return $this->config->items;
52
        } elseif ($this->config->pages) {
53
            return $this->config->pages * $this->config->perPage;
54
        }
55
56
        $pages = $this->config->firstPage == 0 ? $this->config->lastPage + 1 : $this->config->lastPage;
57
58
        return $pages * $this->config->perPage;
59
    }
60
}
61