Skip to content
Closed
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
83 changes: 83 additions & 0 deletions src/Analyser/ArgumentsNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace PHPStan\Analyser;

use PhpParser\Node\Arg;
use PhpParser\Node\Expr\Array_;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\New_;
Expand Down Expand Up @@ -89,6 +90,88 @@
), $acceptsNamedArguments];
}

/**
* @return array{ParametersAcceptor, FuncCall, TrinaryLogic}|null
*/
public static function reorderCallUserFuncArrayArguments(
FuncCall $callUserFuncArrayCall,
Scope $scope,
): ?array
{
$args = $callUserFuncArrayCall->getArgs();
if (count($args) < 2) {
return null;
}

$callbackArg = null;
$argsArrayArg = null;
foreach ($args as $i => $arg) {
if ($callbackArg === null) {
if ($arg->name === null && $i === 0) {
$callbackArg = $arg;
continue;
}
if ($arg->name !== null && ($arg->name->toString() === 'callback' || $arg->name->toString() === 'function')) {
$callbackArg = $arg;
continue;
}
}

if ($argsArrayArg === null) {
if ($arg->name === null && $i === 1) {
$argsArrayArg = $arg;
continue;
}
if ($arg->name !== null && ($arg->name->toString() === 'args' || $arg->name->toString() === 'parameters')) {
$argsArrayArg = $arg;
continue;
}
}
}

if ($callbackArg === null || $argsArrayArg === null) {
return null;
}

if (!$argsArrayArg->value instanceof Array_) {
return null;
}

$calledOnType = $scope->getType($callbackArg->value);
if (!$calledOnType->isCallable()->yes()) {

Check warning on line 141 in src/Analyser/ArgumentsNormalizer.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.3, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ } $calledOnType = $scope->getType($callbackArg->value); - if (!$calledOnType->isCallable()->yes()) { + if ($calledOnType->isCallable()->no()) { return null; }

Check warning on line 141 in src/Analyser/ArgumentsNormalizer.php

View workflow job for this annotation

GitHub Actions / Mutation Testing (8.4, ubuntu-latest)

Escaped Mutant for Mutator "PHPStan\Infection\TrinaryLogicMutator": @@ @@ } $calledOnType = $scope->getType($callbackArg->value); - if (!$calledOnType->isCallable()->yes()) { + if ($calledOnType->isCallable()->no()) { return null; }
return null;
}

$passThruArgs = [];
foreach ($argsArrayArg->value->items as $item) {
$passThruArgs[] = new Arg(
$item->value,
$item->byRef,
$item->unpack,
$item->getAttributes(),
);
}

$callableParametersAcceptors = $calledOnType->getCallableParametersAcceptors($scope);
$parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
$scope,
$passThruArgs,
$callableParametersAcceptors,
null,
);

$acceptsNamedArguments = TrinaryLogic::createYes();
foreach ($callableParametersAcceptors as $callableParametersAcceptor) {
$acceptsNamedArguments = $acceptsNamedArguments->and($callableParametersAcceptor->acceptsNamedArguments());
}

return [$parametersAcceptor, new FuncCall(
$callbackArg->value,
$passThruArgs,
$callUserFuncArrayCall->getAttributes(),
), $acceptsNamedArguments];
}

public static function reorderFuncArguments(
ParametersAcceptor $parametersAcceptor,
FuncCall $functionCall,
Expand Down
9 changes: 9 additions & 0 deletions src/Analyser/ExprHandler/FuncCallHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,15 @@ public function resolveType(MutatingScope $scope, Expr $expr): Type
}
}

if ($functionReflection->getName() === 'call_user_func_array') {
$result = ArgumentsNormalizer::reorderCallUserFuncArrayArguments($expr, $scope);
if ($result !== null) {
[, $innerFuncCall] = $result;

return $scope->getType($innerFuncCall);
}
}

$parametersAcceptor = ParametersAcceptorSelector::selectFromArgs(
$scope,
$expr->getArgs(),
Expand Down
97 changes: 97 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -3535,10 +3535,107 @@ public function processArgs(
}
}

// For call_user_func_array with a resolvable callback, use the callback's
// parameter types for by-reference variables instead of blindly using mixed
if (
$calleeReflection instanceof FunctionReflection
&& $calleeReflection->getName() === 'call_user_func_array'
&& $callLike instanceof FuncCall
) {
$rewriteResult = ArgumentsNormalizer::reorderCallUserFuncArrayArguments($callLike, $scope);
if ($rewriteResult !== null) {
[$callbackParametersAcceptor] = $rewriteResult;
$callbackParameters = $callbackParametersAcceptor->getParameters();
$callArgs = $callLike->getArgs();
if (isset($callArgs[1]) && $callArgs[1]->value instanceof Array_) {
foreach ($callArgs[1]->value->items as $i => $arrayItem) {
// Handle nested by-ref items in sub-arrays
if ($arrayItem->value instanceof Array_) {
$scope = $this->invalidateByRefVariablesInArrayArg($scope, $arrayItem->value);
}

if (!$arrayItem->byRef) {
continue;
}

if (!$arrayItem->value instanceof Variable || !is_string($arrayItem->value->name)) {
continue;
}

$matchedParam = null;
if (isset($callbackParameters[$i])) {
$matchedParam = $callbackParameters[$i];
} elseif (count($callbackParameters) > 0 && $callbackParametersAcceptor->isVariadic()) {
$matchedParam = $callbackParameters[count($callbackParameters) - 1];
}

if ($matchedParam !== null && $matchedParam->passedByReference()->createsNewVariable()) {
$byRefType = $matchedParam->getType();
if (
$matchedParam instanceof ExtendedParameterReflection
&& $matchedParam->getOutType() !== null
) {
$byRefType = $matchedParam->getOutType();
}

$scope = $this->processVirtualAssign(
$scope,
$storage,
$stmt,
$arrayItem->value,
new TypeExpr($byRefType),
$nodeCallback,
)->getScope();
} else {
// Callback parameter is not by-ref or unknown - invalidate to mixed
// since we can't determine what happens with the reference
$scope = $scope->assignVariable($arrayItem->value->name, new MixedType(), new MixedType(), TrinaryLogic::createYes());
}
}
}
} else {
// Could not resolve the callback - fall back to generic invalidation
foreach ($args as $arg) {
$scope = $this->invalidateByRefVariablesInArrayArg($scope, $arg->value);
}
}
} else {
// Invalidate variables passed by reference inside array arguments
// e.g. some_function([&$var, ...]) - $var might be modified
foreach ($args as $arg) {
$scope = $this->invalidateByRefVariablesInArrayArg($scope, $arg->value);
}
}

// not storing this, it's scope after processing all args
return new ExpressionResult($scope, $hasYield, $isAlwaysTerminating, $throwPoints, $impurePoints);
}

private function invalidateByRefVariablesInArrayArg(MutatingScope $scope, Expr $expr): MutatingScope
{
if (!$expr instanceof Array_) {
return $scope;
}

foreach ($expr->items as $arrayItem) {
if ($arrayItem->value instanceof Array_) {
$scope = $this->invalidateByRefVariablesInArrayArg($scope, $arrayItem->value);
}

if (!$arrayItem->byRef) {
continue;
}

if (!$arrayItem->value instanceof Variable || !is_string($arrayItem->value->name)) {
continue;
}

$scope = $scope->assignVariable($arrayItem->value->name, new MixedType(), new MixedType(), TrinaryLogic::createYes());
}

return $scope;
}

/**
* @param MethodReflection|FunctionReflection|null $calleeReflection
*/
Expand Down
78 changes: 78 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-6799.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php declare(strict_types = 1);

namespace Bug6799;

use function PHPStan\Testing\assertType;

class HelloWorld
{
/**
* @param string[] $where
* @param mixed[] $filter
*/
protected function addFilter(array &$where, array $filter, string $value): void
{
if ($value != "" && !empty($filter) && !empty($filter['sql']) && is_string($filter['sql'])) {
$where[] = (string)$filter['sql'] . " = '" . $value . "'";
}
}

/**
* @param string[] $filterValues
* @param mixed[] $filters
*/
protected function test(array $filterValues, array $filters): void
{
if (!empty($filterValues) && !empty($filters)) {
$whereFilter = array();
foreach ($filterValues as $type => $value) {
call_user_func_array(array($this, 'addFilter'), array(&$whereFilter, $filters[$type], $value));
}
assertType('array<string>', $whereFilter);
}
}
}

function testSimple(): void
{
$arr = [];
some_function(1, [&$arr, 'foo']);
assertType('mixed', $arr);
}

function testDirectFunction(): void
{
$result = [];
call_user_func_array('Bug6799\modify_by_ref', [&$result, 'value']);
assertType('array<string>', $result);
}

/** @param callable $callback */
function testUnresolvableCallback($callback): void
{
$arr = [];
call_user_func_array($callback, [&$arr, 'foo']);
assertType('mixed', $arr);
}

function testCallbackNotByRef(): void
{
$arr = [];
call_user_func_array('Bug6799\some_function', [1, [&$arr, 'foo']]);
assertType('mixed', $arr);
}

/**
* @param string[] $arr
*/
function modify_by_ref(array &$arr, string $value): void
{
$arr[] = $value;
}

/**
* @param mixed $x
*/
function some_function(int $a, $x): void
{
}
Loading