Skip to content

Commit 4e0c969

Browse files
committed
Consider named argument flags:JSON_THROW_ON_ERROR for json_ functions as "Safe"
Manually rebasing, adding unit tests, and fixing the tests, for #33
1 parent 33dcbc3 commit 4e0c969

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

src/Rules/UseSafeFunctionsRule.php

+13
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,19 @@ public function processNode(Node $node, Scope $scope): array
3333
$unsafeFunctions = FunctionListLoader::getFunctionList();
3434

3535
if (isset($unsafeFunctions[$functionName])) {
36+
if ($functionName === "json_decode" || $functionName === "json_encode") {
37+
foreach ($node->args as $arg) {
38+
if ($arg instanceof Node\Arg &&
39+
$arg->name instanceof Node\Identifier &&
40+
$arg->name->toLowerString() === "flags"
41+
) {
42+
if ($this->argValueIncludeJSONTHROWONERROR($arg)) {
43+
return [];
44+
}
45+
}
46+
}
47+
}
48+
3649
if ($functionName === "json_decode"
3750
&& $this->argValueIncludeJSONTHROWONERROR($node->getArgs()[3] ?? null)
3851
) {

tests/Rules/UseSafeFunctionsRuleTest.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ public function testExprCall(): void
3737

3838
public function testJSONDecodeNoCatchSafe(): void
3939
{
40-
$this->analyse([__DIR__ . '/data/safe_json_decode_for_7.3.0.php'], []);
40+
$this->analyse([__DIR__ . '/data/safe_json_decode.php'], []);
4141
}
4242

4343
public function testJSONEncodeNoCatchSafe(): void
4444
{
45-
$this->analyse([__DIR__ . '/data/safe_json_encode_for_7.3.0.php'], []);
45+
$this->analyse([__DIR__ . '/data/safe_json_encode.php'], []);
4646
}
4747
}
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
<?php
22

3+
// Test various combinations of flags
34
json_decode("{}", true, 512, JSON_THROW_ON_ERROR);
45
json_decode("{}", true, 512, JSON_INVALID_UTF8_IGNORE | JSON_THROW_ON_ERROR);
56
json_decode("{}", true, 512, JSON_INVALID_UTF8_IGNORE | JSON_OBJECT_AS_ARRAY | JSON_THROW_ON_ERROR);
67

8+
// Test raw integers too
79
json_decode("{}", true, 512, 4194304);
810
json_decode("{}", true, 512, 1048576 | 4194304);
911
json_decode("{}", true, 512, 1048576 | 1 | 4194304);
12+
13+
// Test named arguments instead of positional
14+
json_decode("{}", flags: JSON_THROW_ON_ERROR);

tests/Rules/data/safe_json_encode_for_7.3.0.php renamed to tests/Rules/data/safe_json_encode.php

+2
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,5 @@
33
json_encode([], JSON_THROW_ON_ERROR, 512);
44
json_encode([], JSON_FORCE_OBJECT | JSON_THROW_ON_ERROR, 512);
55
json_encode([], JSON_FORCE_OBJECT | JSON_INVALID_UTF8_IGNORE | JSON_THROW_ON_ERROR, 512);
6+
7+
json_encode([], flags: JSON_THROW_ON_ERROR);

0 commit comments

Comments
 (0)