From 73d38e2751e9445ff80561d8558bab537995fd79 Mon Sep 17 00:00:00 2001 From: Shish Date: Wed, 19 Feb 2025 23:24:19 +0000 Subject: [PATCH] Consider named argument flags:JSON_THROW_ON_ERROR for json_ functions as "Safe" Manually rebasing, adding unit tests, and fixing the tests, for #33 --- src/Rules/UseSafeFunctionsRule.php | 13 +++++++++++++ tests/Rules/UseSafeFunctionsRuleTest.php | 4 ++-- ...on_decode_for_7.3.0.php => safe_json_decode.php} | 5 +++++ ...on_encode_for_7.3.0.php => safe_json_encode.php} | 2 ++ 4 files changed, 22 insertions(+), 2 deletions(-) rename tests/Rules/data/{safe_json_decode_for_7.3.0.php => safe_json_decode.php} (70%) rename tests/Rules/data/{safe_json_encode_for_7.3.0.php => safe_json_encode.php} (81%) diff --git a/src/Rules/UseSafeFunctionsRule.php b/src/Rules/UseSafeFunctionsRule.php index a137779..aaba401 100644 --- a/src/Rules/UseSafeFunctionsRule.php +++ b/src/Rules/UseSafeFunctionsRule.php @@ -33,6 +33,19 @@ public function processNode(Node $node, Scope $scope): array $unsafeFunctions = FunctionListLoader::getFunctionList(); if (isset($unsafeFunctions[$functionName])) { + if ($functionName === "json_decode" || $functionName === "json_encode") { + foreach ($node->args as $arg) { + if ($arg instanceof Node\Arg && + $arg->name instanceof Node\Identifier && + $arg->name->toLowerString() === "flags" + ) { + if ($this->argValueIncludeJSONTHROWONERROR($arg)) { + return []; + } + } + } + } + if ($functionName === "json_decode" && $this->argValueIncludeJSONTHROWONERROR($node->getArgs()[3] ?? null) ) { diff --git a/tests/Rules/UseSafeFunctionsRuleTest.php b/tests/Rules/UseSafeFunctionsRuleTest.php index 55ba182..014bd6d 100644 --- a/tests/Rules/UseSafeFunctionsRuleTest.php +++ b/tests/Rules/UseSafeFunctionsRuleTest.php @@ -37,11 +37,11 @@ public function testExprCall(): void public function testJSONDecodeNoCatchSafe(): void { - $this->analyse([__DIR__ . '/data/safe_json_decode_for_7.3.0.php'], []); + $this->analyse([__DIR__ . '/data/safe_json_decode.php'], []); } public function testJSONEncodeNoCatchSafe(): void { - $this->analyse([__DIR__ . '/data/safe_json_encode_for_7.3.0.php'], []); + $this->analyse([__DIR__ . '/data/safe_json_encode.php'], []); } } diff --git a/tests/Rules/data/safe_json_decode_for_7.3.0.php b/tests/Rules/data/safe_json_decode.php similarity index 70% rename from tests/Rules/data/safe_json_decode_for_7.3.0.php rename to tests/Rules/data/safe_json_decode.php index c69e7ca..22b450a 100644 --- a/tests/Rules/data/safe_json_decode_for_7.3.0.php +++ b/tests/Rules/data/safe_json_decode.php @@ -1,9 +1,14 @@