Passed
Branch feature/first-release (ffa532)
by Andrea Marco
02:07
created

NextPageHandler::handle()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 10
cc 2
nc 1
nop 0
crap 2
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 5
    public function matches(): bool
23
    {
24 5
        return !!$this->config->nextPageKey;
25
    }
26
27
    /**
28
     * Handle the APIs configuration
29
     *
30
     * @return Traversable
31
     */
32 2
    public function handle(): Traversable
33
    {
34 2
        yield from $this->retry(function (Outcome $outcome) {
35
            try {
36 2
                yield from $this->handleByNextPage();
37 1
            } catch (Throwable $e) {
38 1
                $outcome->addFailedPage($this->config->nextPage);
39 1
                throw $e;
40
            }
41 2
        });
42 1
    }
43
44
    /**
45
     * Handle APIs with next page
46
     *
47
     * @return Traversable
48
     */
49 2
    protected function handleByNextPage(): Traversable
50
    {
51 2
        $request = clone $this->config->source->request;
52
53 2
        yield from $this->config->source->json($this->config->path);
54
55 2
        while ($this->config->nextPage) {
56 2
            $uri = Uri::withQueryValue($request->getUri(), $this->config->pageName, $this->config->nextPage);
57 2
            $this->config->source = new SourceWrapper($request->withUri($uri));
58 2
            $this->config->nextPage($this->config->nextPageKey);
59 2
            yield from $this->handleByNextPage();
60
        }
61 1
    }
62
}
63