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

NextPageHandler::handleByNextPage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
dl 0
loc 11
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Cerbero\LazyJsonPages\Handlers;
4
5
use Cerbero\LazyJsonPages\Outcome;
6
use Cerbero\LazyJsonPages\SourceWrapper;
7
use GuzzleHttp\Psr7\Uri;
8
use Throwable;
9
use Traversable;
10
11
/**
12
 * The next page handler.
13
 *
14
 */
15
class NextPageHandler extends AbstractHandler
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->nextPageKey;
25
    }
26
27
    /**
28
     * Handle the APIs configuration
29
     *
30
     * @return Traversable
31
     */
32
    public function handle(): Traversable
33
    {
34
        yield from $this->retry(function (Outcome $outcome) {
35
            try {
36
                yield from $this->handleByNextPage();
37
            } catch (Throwable $e) {
38
                $outcome->addFailedPage($this->config->nextPage);
39
                throw $e;
40
            }
41
        });
42
    }
43
44
    /**
45
     * Handle APIs with next page
46
     *
47
     * @return Traversable
48
     */
49
    protected function handleByNextPage(): Traversable
50
    {
51
        $request = clone $this->config->source->request;
52
53
        yield from $this->config->source->json($this->config->path);
54
55
        while ($this->config->nextPage) {
56
            $uri = Uri::withQueryValue($request->getUri(), $this->config->pageName, $this->config->nextPage);
57
            $this->config->source = new SourceWrapper($request->withUri($uri));
58
            $this->config->nextPage($this->config->nextPageKey);
59
            yield from $this->handleByNextPage();
60
        }
61
    }
62
}
63