28
28
*
29
29
* @experimental
30
30
*/
31
- final class JsonCrawler implements JsonCrawlerInterface
31
+ final class JsonCrawler implements CrawlerInterface, JsonCrawlerInterface
32
32
{
33
33
private const RFC9535_FUNCTIONS = [
34
34
'length ' => true ,
@@ -39,14 +39,25 @@ final class JsonCrawler implements JsonCrawlerInterface
39
39
];
40
40
41
41
/**
42
- * @param resource|string $raw
42
+ * @var resource|string|array|null
43
43
*/
44
- public function __construct (
45
- private readonly mixed $ raw ,
46
- ) {
47
- if (!\is_string ($ raw ) && !\is_resource ($ raw )) {
48
- throw new InvalidArgumentException (\sprintf ('Expected string or resource, got "%s". ' , get_debug_type ($ raw )));
44
+ private mixed $ raw ;
45
+
46
+ /**
47
+ * @param resource|string|array|null $data
48
+ */
49
+ public function __construct (mixed $ data = [])
50
+ {
51
+ if (!\is_string ($ data ) && !\is_resource ($ data ) && !\is_array ($ data )) {
52
+ throw new \TypeError (\sprintf ('Argument #1 ($data) must be of type string, array or resource, %s given. ' , get_debug_type ($ data )));
49
53
}
54
+
55
+ $ this ->raw = $ data ;
56
+ }
57
+
58
+ public function fromJson (mixed $ data ): CrawlerInterface
59
+ {
60
+ return new self ($ data );
50
61
}
51
62
52
63
public function find (string |JsonPath $ query ): array
@@ -74,13 +85,17 @@ private function evaluate(JsonPath $query): array
74
85
$ json = $ simplified ['json ' ];
75
86
}
76
87
77
- try {
78
- $ data = json_decode ($ json , true , 512 , \JSON_THROW_ON_ERROR );
79
- } catch (\JsonException $ e ) {
80
- throw new InvalidJsonStringInputException ($ e ->getMessage (), $ e );
81
- }
88
+ if (\is_array ($ json )) {
89
+ $ current = [$ json ];
90
+ } else {
91
+ try {
92
+ $ data = json_decode ($ json , true , 512 , \JSON_THROW_ON_ERROR );
93
+ } catch (\JsonException $ e ) {
94
+ throw new InvalidJsonStringInputException ($ e ->getMessage (), $ e );
95
+ }
82
96
83
- $ current = [$ data ];
97
+ $ current = [$ data ];
98
+ }
84
99
85
100
foreach ($ tokens as $ token ) {
86
101
$ next = [];
0 commit comments