Skip to content

Commit

Permalink
Consider named argument flags:JSON_THROW_ON_ERROR for json_ functions…
Browse files Browse the repository at this point in the history
… as "Safe"

Manually rebasing, adding unit tests, and fixing the tests, for #33
  • Loading branch information
shish committed Feb 19, 2025
1 parent 33dcbc3 commit 4e0c969
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
13 changes: 13 additions & 0 deletions src/Rules/UseSafeFunctionsRule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
) {
Expand Down
4 changes: 2 additions & 2 deletions tests/Rules/UseSafeFunctionsRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'], []);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
<?php

// Test various combinations of flags
json_decode("{}", true, 512, JSON_THROW_ON_ERROR);
json_decode("{}", true, 512, JSON_INVALID_UTF8_IGNORE | JSON_THROW_ON_ERROR);
json_decode("{}", true, 512, JSON_INVALID_UTF8_IGNORE | JSON_OBJECT_AS_ARRAY | JSON_THROW_ON_ERROR);

// Test raw integers too
json_decode("{}", true, 512, 4194304);
json_decode("{}", true, 512, 1048576 | 4194304);
json_decode("{}", true, 512, 1048576 | 1 | 4194304);

// Test named arguments instead of positional
json_decode("{}", flags: JSON_THROW_ON_ERROR);
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
json_encode([], JSON_THROW_ON_ERROR, 512);
json_encode([], JSON_FORCE_OBJECT | JSON_THROW_ON_ERROR, 512);
json_encode([], JSON_FORCE_OBJECT | JSON_INVALID_UTF8_IGNORE | JSON_THROW_ON_ERROR, 512);

json_encode([], flags: JSON_THROW_ON_ERROR);

0 comments on commit 4e0c969

Please sign in to comment.