Passed
Push — master ( 342193...f80fe6 )
by Andrea Marco
03:14 queued 11s
created

NextPageHandler   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 46
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 16
c 1
b 0
f 0
dl 0
loc 46
ccs 19
cts 19
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A matches() 0 3 1
A handle() 0 9 2
A handleByNextPage() 0 11 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->retryYielding(function (Outcome $outcome) {
35
            try {
36 2
                yield from $this->handleByNextPage();
37 1
            } catch (Throwable $e) {
38 1
                $outcome->pullFailedPages();
39 1
                $outcome->addFailedPage($this->config->nextPage);
40 1
                throw $e;
41
            }
42 2
        });
43 1
    }
44
45
    /**
46
     * Handle APIs with next page
47
     *
48
     * @return Traversable
49
     */
50 2
    protected function handleByNextPage(): Traversable
51
    {
52 2
        $request = clone $this->config->source->request;
53
54 2
        yield from $this->config->source->json($this->config->path);
55
56 2
        while ($this->config->nextPage) {
57 2
            $uri = Uri::withQueryValue($request->getUri(), $this->config->pageName, $this->config->nextPage);
58 2
            $this->config->source = new SourceWrapper($request->withUri($uri));
59 2
            $this->config->nextPage($this->config->nextPageKey);
60 2
            yield from $this->handleByNextPage();
61
        }
62 1
    }
63
}
64