Skip to content

Commit

Permalink
Reindex constant arrays via shuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
herndlm authored and ondrejmirtes committed Jun 17, 2022
1 parent 4482fe4 commit eff6b2c
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/Analyser/NodeScopeResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1921,6 +1921,17 @@ static function (?Type $offsetType, Type $valueType, bool $optional) use (&$arra
$scope = $scope->assignVariable('http_response_header', new ArrayType(new IntegerType(), new StringType()));
}

if (isset($functionReflection) && $functionReflection->getName() === 'shuffle') {
$arrayArg = $expr->getArgs()[0]->value;
$arrayArgType = $scope->getType($arrayArg);

if ($arrayArgType instanceof ConstantArrayType) {
$arrayArgType = $arrayArgType->getValuesArray();
}

$scope = $scope->specifyExpressionType($arrayArg, $arrayArgType, $arrayArgType);
}

if (
isset($functionReflection)
&& $functionReflection->getName() === 'array_splice'
Expand Down
1 change: 1 addition & 0 deletions tests/PHPStan/Analyser/NodeScopeResolverTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,7 @@ public function dataFileAsserts(): iterable
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6070.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6108.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-1516.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6138.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-6174.php');
yield from $this->gatherAssertTypes(__DIR__ . '/../Rules/Methods/data/bug-5749.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/bug-5675.php');
Expand Down
29 changes: 29 additions & 0 deletions tests/PHPStan/Analyser/data/bug-6138.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<?php declare(strict_types = 1);

namespace Bug6138;

use function PHPStan\Testing\assertType;

$indexed = [
1,
2,
3,
];
$associative = [
'a' => 1,
'b' => 2,
'c' => 3,
];
$unordered = [
0 => 1,
3 => 2,
42 => 3,
];

shuffle( $indexed );
shuffle( $associative );
shuffle( $unordered );

assertType( 'array{0, 1, 2}', array_keys( $indexed ) );
assertType( 'array{0, 1, 2}', array_keys( $associative ) );
assertType( 'array{0, 1, 2}', array_keys( $unordered ) );

0 comments on commit eff6b2c

Please sign in to comment.