Skip to content

Commit 43affe9

Browse files
committed
fix: improve JSON validation in isJson() and loadJsonAsArray() methods
1 parent 88937ab commit 43affe9

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

src/FeedIo/Reader/Document.php

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,15 @@ public function startWith(string $character): bool
2828

2929
public function isJson(): bool
3030
{
31-
if (! $this->startWith('{')) {
31+
if (! $this->startWith('{') && ! $this->startWith('[')) {
32+
return false;
33+
}
34+
try {
35+
json_decode($this->content, false, 512, JSON_THROW_ON_ERROR);
36+
return true;
37+
} catch (\JsonException $e) {
3238
return false;
3339
}
34-
35-
json_decode($this->content);
36-
37-
return json_last_error() === JSON_ERROR_NONE;
3840
}
3941

4042
public function isXml(): bool
@@ -72,7 +74,7 @@ protected function loadDomDocument(): DOMDocument
7274
* @param string $errno
7375
*/
7476
function ($errno, $errstr) {
75-
throw new \InvalidArgumentException("malformed xml string. parsing error : $errstr ($errno)");
77+
throw new \InvalidArgumentException("malformed xml string. parsing error: $errstr ($errno)");
7678
}
7779
);
7880

@@ -100,6 +102,12 @@ protected function loadJsonAsArray(): array
100102
);
101103
}
102104

105+
if (! is_array($result)) {
106+
throw new \InvalidArgumentException(
107+
'JSON content must decode to an array or object, got: ' . gettype($result)
108+
);
109+
}
110+
103111
return $result;
104112
}
105113
}

0 commit comments

Comments
 (0)