Skip to content

Commit

Permalink
Fix nextAutoIndexes in array coming from ArrayCombineFunctionReturnTy…
Browse files Browse the repository at this point in the history
…peExtension
  • Loading branch information
ondrejmirtes committed Oct 7, 2024
1 parent 0df14b1 commit c4ba434
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 5 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/e2e-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,9 @@ jobs:
cd e2e/discussion-11362
composer install
../../bin/phpstan
- script: |
cd e2e/bug-11819
../../bin/phpstan
steps:
- name: "Checkout"
Expand Down
4 changes: 4 additions & 0 deletions e2e/bug-11819/phpstan.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
parameters:
level: 5
paths:
- test.php
11 changes: 11 additions & 0 deletions e2e/bug-11819/test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php declare(strict_types = 1);

const TYPES = [1, 2, 3];

$types = array_combine(TYPES, array_fill(0, \count(TYPES), false));

$test = rand(1, 4);

if (isset($types[$test])) {
$types[$test] = true;
}
13 changes: 8 additions & 5 deletions src/Type/Php/ArrayCombineFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantArrayTypeBuilder;
use PHPStan\Type\Constant\ConstantBooleanType;
use PHPStan\Type\Constant\ConstantIntegerType;
use PHPStan\Type\Constant\ConstantStringType;
Expand Down Expand Up @@ -62,11 +63,13 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,

$keyTypes = $this->sanitizeConstantArrayKeyTypes($keyTypes);
if ($keyTypes !== null) {
return new ConstantArrayType(
$keyTypes,
$valueTypes,
$keysParamType->getNextAutoIndexes(),
);
$builder = ConstantArrayTypeBuilder::createEmpty();
foreach ($keyTypes as $i => $keyType) {
$valueType = $valueTypes[$i];
$builder->setOffsetValueType($keyType, $valueType);
}

return $builder->getArray();
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/PHPStan/Analyser/nsrt/array-combine-php8.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,3 +83,11 @@ function withDifferentNumberOfElements(): void
{
assertType('*NEVER*', array_combine(['foo'], ['bar', 'baz']));
}

function bug11819(): void
{
$keys = [1, 2, 3];
$types = array_combine($keys, array_fill(0, \count($keys), false));
$types[] = 'foo';
assertType('array{1: false, 2: false, 3: false, 4: \'foo\'}', $types);
}

0 comments on commit c4ba434

Please sign in to comment.