1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cerbero\LazyJson; |
4
|
|
|
|
5
|
|
|
use Cerbero\LazyJson\Exceptions\LazyJsonException; |
6
|
|
|
use Cerbero\LazyJson\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 JSON. |
18
|
|
|
* |
19
|
|
|
* @var Traversable |
20
|
|
|
*/ |
21
|
|
|
protected $traversable; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* The source handlers. |
25
|
|
|
* |
26
|
|
|
* @var array |
27
|
|
|
*/ |
28
|
|
|
protected $handlers = [ |
29
|
|
|
Handlers\Endpoint::class, |
30
|
|
|
Handlers\Filename::class, |
31
|
|
|
Handlers\IterableSource::class, |
32
|
|
|
Handlers\JsonString::class, |
33
|
|
|
Handlers\LaravelClientResponse::class, |
34
|
|
|
Handlers\Psr7Message::class, |
35
|
|
|
Handlers\Psr7Stream::class, |
36
|
|
|
Handlers\Resource::class, |
37
|
|
|
]; |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Instantiate the class. |
41
|
|
|
* |
42
|
|
|
* @param mixed $source |
43
|
|
|
* @param string $path |
44
|
|
|
*/ |
45
|
9 |
|
public function __construct($source, string $path) |
46
|
|
|
{ |
47
|
9 |
|
$this->traversable = $this->toTraversable($source, $path); |
48
|
8 |
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Turn the given JSON source into a traversable instance |
52
|
|
|
* |
53
|
|
|
* @param mixed $source |
54
|
|
|
* @param string $path |
55
|
|
|
* @return Traversable |
56
|
|
|
* |
57
|
|
|
* @throws LazyJsonException |
58
|
|
|
*/ |
59
|
9 |
|
protected function toTraversable($source, string $path): Traversable |
60
|
|
|
{ |
61
|
9 |
|
foreach ($this->handlers as $class) { |
62
|
|
|
/** @var Handlers\Handler $handler */ |
63
|
9 |
|
$handler = new $class(); |
64
|
|
|
|
65
|
9 |
|
if ($handler->handles($source)) { |
66
|
8 |
|
return $handler->handle($source, $path); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
throw new LazyJsonException('Unable to load the JSON from the provided source.'); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Retrieve the traversable JSON |
75
|
|
|
* |
76
|
|
|
* @return Traversable |
77
|
|
|
*/ |
78
|
8 |
|
public function getIterator(): Traversable |
79
|
|
|
{ |
80
|
8 |
|
return $this->traversable; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|