Skip to content

Commit 47200cc

Browse files
authored
Merge pull request #6 from magefan/12113-improved-json-validator
12113 Imrpoved JSON Validator
2 parents 6983020 + 563d6ee commit 47200cc

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

Model/Parser/Html.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,8 @@ public function __construct(
9494
*/
9595
public function execute(string $output): string
9696
{
97-
$isOutputIsJson = (strpos($output, '{"') === 0 && strrpos($output, '"}') === strlen($output) - 2);
98-
97+
$isOutputIsJson = $this->json_validate($output);
98+
9999
$productIds = $this->getProductIds($output);
100100
[$ruleIds, $productIdRuleIds] = $this->getProductIdsToRuleIdsMap->execute($productIds);
101101

@@ -187,4 +187,20 @@ private function getProductIds(string $html): array
187187

188188
return $productIds;
189189
}
190+
191+
private function json_validate($json, $depth = 512, $flags = 0)
192+
{
193+
// First character check to ensure the string starts with `{` or `[` (to improve perfrormace)
194+
$trimmedJson = ltrim($json);
195+
if (!is_string($json) || ($trimmedJson[0] !== '{' && $trimmedJson[0] !== '[')) {
196+
return false;
197+
}
198+
199+
try {
200+
json_decode($json, false, $depth, $flags | JSON_THROW_ON_ERROR);
201+
return true;
202+
} catch (\JsonException $e) {
203+
return false;
204+
}
205+
}
190206
}

0 commit comments

Comments
 (0)