1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cerbero\JsonParser\Sources; |
4
|
|
|
|
5
|
|
|
use Cerbero\JsonParser\Exceptions\UnsupportedSourceException; |
6
|
|
|
use Generator; |
7
|
|
|
use Traversable; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* The handler of any JSON source. |
11
|
|
|
* |
12
|
|
|
*/ |
13
|
|
|
class AnySource extends Source |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The supported sources. |
17
|
|
|
* |
18
|
|
|
* @var class-string<Source>[] |
|
|
|
|
19
|
|
|
*/ |
20
|
|
|
protected array $supportedSources = [ |
21
|
|
|
CustomSource::class, |
22
|
|
|
Endpoint::class, |
23
|
|
|
Filename::class, |
24
|
|
|
IterableSource::class, |
25
|
|
|
Json::class, |
26
|
|
|
JsonResource::class, |
27
|
|
|
LaravelClientResponse::class, |
28
|
|
|
Psr7Message::class, |
29
|
|
|
Psr7Request::class, |
30
|
|
|
Psr7Stream::class, |
31
|
|
|
]; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* The matching source. |
35
|
|
|
* |
36
|
|
|
* @var Source|null |
37
|
|
|
*/ |
38
|
|
|
protected ?Source $matchingSource; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* Retrieve the JSON fragments |
42
|
|
|
* |
43
|
|
|
* @return Traversable<int, string> |
44
|
|
|
* @throws UnsupportedSourceException |
45
|
|
|
*/ |
46
|
361 |
|
public function getIterator(): Traversable |
47
|
|
|
{ |
48
|
361 |
|
return $this->matchingSource(); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* Retrieve the matching source |
53
|
|
|
* |
54
|
|
|
* @return Source |
55
|
|
|
* @throws UnsupportedSourceException |
56
|
|
|
*/ |
57
|
361 |
|
protected function matchingSource(): Source |
58
|
|
|
{ |
59
|
361 |
|
if (isset($this->matchingSource)) { |
60
|
2 |
|
return $this->matchingSource; |
61
|
|
|
} |
62
|
|
|
|
63
|
361 |
|
foreach ($this->sources() as $source) { |
64
|
361 |
|
if ($source->matches()) { |
65
|
360 |
|
return $this->matchingSource = $source; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
1 |
|
throw new UnsupportedSourceException($this->source); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Retrieve all available sources |
74
|
|
|
* |
75
|
|
|
* @return Generator<int, Source> |
76
|
|
|
*/ |
77
|
361 |
|
protected function sources(): Generator |
78
|
|
|
{ |
79
|
361 |
|
foreach ($this->supportedSources as $source) { |
80
|
361 |
|
yield new $source($this->source, $this->config); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
/** |
85
|
|
|
* Determine whether the JSON source can be handled |
86
|
|
|
* |
87
|
|
|
* @return bool |
88
|
|
|
*/ |
89
|
1 |
|
public function matches(): bool |
90
|
|
|
{ |
91
|
1 |
|
return true; |
92
|
|
|
} |
93
|
|
|
|
94
|
|
|
/** |
95
|
|
|
* Retrieve the calculated size of the JSON source |
96
|
|
|
* |
97
|
|
|
* @return int|null |
98
|
|
|
*/ |
99
|
2 |
|
protected function calculateSize(): ?int |
100
|
|
|
{ |
101
|
2 |
|
return $this->matchingSource()->size(); |
102
|
|
|
} |
103
|
|
|
} |
104
|
|
|
|