Skip to content

Commit

Permalink
Merge pull request #9975 from kkmuffme/sprintf-single-arg-splat-array
Browse files Browse the repository at this point in the history
Fix sprintf single arg splat array
  • Loading branch information
orklah committed Jul 2, 2023
2 parents 3c3d184 + 62475cb commit 53ce62b
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 15 deletions.
Expand Up @@ -47,21 +47,6 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
$statements_source = $event->getStatementsSource();
$call_args = $event->getCallArgs();

// it makes no sense to use sprintf/printf when there is only 1 arg (the format)
// as it wouldn't have any placeholders
if (count($call_args) === 1) {
IssueBuffer::maybeAdd(
new TooFewArguments(
'Too few arguments for ' . $event->getFunctionId() . ', expecting at least 2 arguments',
$event->getCodeLocation(),
$event->getFunctionId(),
),
$statements_source->getSuppressedIssues(),
);

return null;
}

$has_splat_args = false;
$node_type_provider = $statements_source->getNodeTypeProvider();
foreach ($call_args as $call_arg) {
Expand All @@ -78,6 +63,28 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
}
}

// there is only 1 array argument, fall back to the default handling
// eventually this could be refined
// to check if it's an array with literal string as first element for further checking
if (count($call_args) === 1 && $has_splat_args === true) {
return null;
}

// it makes no sense to use sprintf/printf when there is only 1 arg (the format)
// as it wouldn't have any placeholders
if (count($call_args) === 1) {
IssueBuffer::maybeAdd(
new TooFewArguments(
'Too few arguments for ' . $event->getFunctionId() . ', expecting at least 2 arguments',
$event->getCodeLocation(),
$event->getFunctionId(),
),
$statements_source->getSuppressedIssues(),
);

return null;
}

// PHP 7 handling for formats that do not contain anything but placeholders
$is_falsable = true;
foreach ($call_args as $index => $call_arg) {
Expand Down
12 changes: 12 additions & 0 deletions tests/ReturnTypeProvider/SprintfTest.php
Expand Up @@ -213,6 +213,18 @@ public function providerValidCodeParse(): iterable
],
];

yield 'sprintfSplatUnpackingArraySingleArg' => [
'code' => '<?php
$a = ["Hello %s", "Sam"];
$val = sprintf(...$a);
',
'assertions' => [
'$val===' => 'string',
],
'ignored_issues' => [],
'php_version' => '8.0',
];

yield 'sprintfMultiplePlaceholdersNoErrorsIssue9941PHP7' => [
'code' => '<?php
$val = sprintf("Handling product %d => %d (%d)", 123, 456, 789);
Expand Down

0 comments on commit 53ce62b

Please sign in to comment.