Skip to content

Consider named argument flags:JSON_THROW_ON_ERROR for json_ functions as "Safe" #56

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);