|
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
|
|
|
|