Skip to content

Commit

Permalink
run format checks for splat too
Browse files Browse the repository at this point in the history
  • Loading branch information
kkmuffme committed Jun 24, 2023
1 parent 9599c24 commit 28b9e8d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,9 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
return null;
}

$has_splat_args = false;
$node_type_provider = $statements_source->getNodeTypeProvider();
foreach ($call_args as $index => $call_arg) {
foreach ($call_args as $call_arg) {
$type = $node_type_provider->getType($call_arg->value);
if ($type === null) {
continue;
Expand All @@ -72,7 +73,8 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
// if it's an array, used with splat operator
// we cannot validate it reliably below and report false positive errors
if ($type->isArray()) {
return null;
$has_splat_args = true;
break;
}
}

Expand Down Expand Up @@ -137,7 +139,8 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
return Type::getString();
}

$provided_placeholders_count = count($call_args) - 1;
// assume a random, high number for tests
$provided_placeholders_count = $has_splat_args === true ? 100 : count($call_args) - 1;
$dummy = array_fill(0, $provided_placeholders_count, '');

// check if we have enough/too many arguments and a valid format
Expand Down Expand Up @@ -229,6 +232,11 @@ public static function getFunctionReturnType(FunctionReturnTypeProviderEvent $ev
return Type::getFalse();
}

// we can only validate the format and arg 1 when using splat
if ($has_splat_args === true) {
break;
}

if (is_string($result) && count($dummy) + 1 <= $provided_placeholders_count) {
IssueBuffer::maybeAdd(
new TooManyArguments(
Expand Down
12 changes: 11 additions & 1 deletion tests/ReturnTypeProvider/SprintfTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -186,12 +186,22 @@ public function providerValidCodeParse(): iterable
yield 'sprintfSplatUnpackingArray' => [
'code' => '<?php
$a = ["a", "b", "c"];
$val = sprintf("%s %s %s", ...$a);
$val = sprintf("%s%s%s", ...$a);
',
'assertions' => [
'$val===' => 'string',
],
];

yield 'sprintfSplatUnpackingArrayNonEmpty' => [
'code' => '<?php
$a = ["a", "b", "c"];
$val = sprintf("%s %s %s", ...$a);
',
'assertions' => [
'$val===' => 'non-empty-string',
],
];
}

public function providerInvalidCodeParse(): iterable
Expand Down

0 comments on commit 28b9e8d

Please sign in to comment.