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

NextPageHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 15
c 1
b 0
f 0
dl 0
loc 45
ccs 18
cts 18
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A matches() 0 3 1
A handleByNextPage() 0 11 2
A handle() 0 8 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