Skip to content

Commit 177821d

Browse files
SanderMullerclaude
andauthored
Require array_search()'s haystack argument before reading it (#6239)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 7550443 commit 177821d

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

src/Analyser/ExprHandler/AssignHandler.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1912,7 +1912,7 @@ private function shouldKeepList(ArrayDimFetch $arrayDimFetch, Scope $scope, Type
19121912
$arrayDimFetch->dim instanceof Expr\FuncCall
19131913
&& $arrayDimFetch->dim->name instanceof Name
19141914
&& $arrayDimFetch->dim->name->toLowerString() === 'array_search'
1915-
&& count($arrayDimFetch->dim->getArgs()) >= 1
1915+
&& count($arrayDimFetch->dim->getArgs()) >= 2 // the haystack is the second argument
19161916
&& $this->isSameVariable($arrayDimFetch->var, $arrayDimFetch->dim->getArgs()[1]->value)
19171917
) {
19181918
return true;
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace ArraySearchOffsetArgumentCount;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
function singleArgument(): void
8+
{
9+
$list = [1, 2, 3];
10+
// the haystack is array_search()'s second argument, so a call without one cannot be the
11+
// list-preserving idiom - the call itself is reported as invalid
12+
$list[array_search($list)] = 4;
13+
assertType('array{1|4, 2|4, 3|4, ...<int<min, -1>|int<3, max>|string, 4>}', $list);
14+
}
15+
16+
/**
17+
* @param array{int, list<int>} $args
18+
*/
19+
function unpackedArguments(array $args): void
20+
{
21+
$list = [1, 2, 3];
22+
$list[array_search(...$args)] = 4;
23+
assertType('array{1|4, 2|4, 3|4, ...<int<min, -1>|int<3, max>|string, 4>}', $list);
24+
}

0 commit comments

Comments
 (0)