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

Source::toTraversable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 5
c 2
b 0
f 0
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 3
nop 1
crap 3
1
<?php
2
3
namespace Cerbero\LazyJsonPages;
4
5
use Cerbero\LazyJsonPages\Exceptions\LazyJsonPagesException;
6
use Cerbero\LazyJsonPages\Handlers;
7
use IteratorAggregate;
8
use Traversable;
9
10
/**
11
 * The JSON source.
12
 *
13
 */
14
class Source implements IteratorAggregate
15
{
16
    /**
17
     * The traversable items.
18
     *
19
     * @var Traversable
20
     */
21
    protected $traversable;
22
23
    /**
24
     * The pagination handlers.
25
     *
26
     * @var array
27
     */
28
    protected $handlers = [
29
        Handlers\TotalPagesHandler::class,
30
        Handlers\TotalItemsHandler::class,
31
        Handlers\ItemsPerPageHandler::class,
32
        Handlers\NextPageHandler::class,
33
        Handlers\LastPageHandler::class,
34
    ];
35
36
    /**
37
     * Instantiate the class.
38
     *
39
     * @param \Psr\Http\Message\RequestInterface|\Illuminate\Http\Client\Response $source
40
     * @param string $path
41
     * @param callable|array|string|int $config
42
     */
43 14
    public function __construct($source, string $path, $config)
44
    {
45 14
        $this->traversable = $this->toTraversable(new Config($source, $path, $config));
46 13
    }
47
48
    /**
49
     * Retrieve the traversable items depending on the given configuration
50
     *
51
     * @param Config $config
52
     * @return Traversable
53
     *
54
     * @throws LazyJsonPagesException
55
     */
56 14
    protected function toTraversable(Config $config): Traversable
57
    {
58 14
        foreach ($this->handlers as $class) {
59
            /** @var Handlers\AbstractHandler $handler */
60 14
            $handler = new $class($config);
61
62 14
            if ($handler->matches()) {
63 13
                return $handler->handle();
64
            }
65
        }
66
67 1
        throw new LazyJsonPagesException('Unable to load paginated items from the provided source.');
68
    }
69
70
    /**
71
     * Retrieve the traversable items
72
     *
73
     * @return Traversable
74
     */
75 13
    public function getIterator(): Traversable
76
    {
77 13
        return $this->traversable;
78
    }
79
}
80