Skip to content
Merged
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
20 changes: 9 additions & 11 deletions src/Type/Php/ArrayKeyExistsFunctionTypeSpecifyingExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -77,17 +77,15 @@ public function specifyTypes(
if ($context->true()) {
$specifiedTypes = new SpecifiedTypes();

if (count($keyType->getConstantScalarTypes()) <= 1) {
$nonEmptyType = $arrayType->isArray()->yes()
? new NonEmptyArrayType()
: TypeCombinator::intersect(new ArrayType(new MixedType(), new MixedType()), new NonEmptyArrayType());
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$array,
$nonEmptyType,
$context,
$scope,
));
}
$nonEmptyType = $arrayType->isArray()->yes()
? new NonEmptyArrayType()
: TypeCombinator::intersect(new ArrayType(new MixedType(), new MixedType()), new NonEmptyArrayType());
$specifiedTypes = $specifiedTypes->unionWith($this->typeSpecifier->create(
$array,
$nonEmptyType,
$context,
$scope,
));

if ($arrayType->isIterableAtLeastOnce()->no()) {
return $specifiedTypes;
Expand Down
46 changes: 46 additions & 0 deletions tests/PHPStan/Analyser/nsrt/bug-14489.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php declare(strict_types = 1);

namespace Bug14489;

use function array_key_exists;
use function array_merge;
use function array_unique;
use function array_values;
use function PHPStan\Testing\assertType;

function () {
$data = [['c1' => [1], 'c2' => [4]]];

$cData = [];
foreach ($data as $cMap) {
foreach ($cMap as $c => $ids) {
if (array_key_exists($c, $cData)) {
$cData[$c] = array_unique(array_merge($cData[$c], $ids));
} else {
$cData[$c] = $ids;
}
}
}

$values = array_values($cData);
assertType('non-empty-list<non-empty-array<0|1, 1|4>>', $values);
};

function () {
/** @var 'c1'|'c2' $c */
$c = 'c1';
/** @var array{1}|array{4} $ids */
$ids = [1];

$cData = [];
while (rand(0, 1)) {
if (array_key_exists($c, $cData)) {
assertType('non-empty-array<\'c1\'|\'c2\', array{1}|array{4}>', $cData);
assertType('array{1}|array{4}', $cData[$c]);
$cData[$c] = $cData[$c];
} else {
$cData[$c] = $ids;
}
}
assertType('array<\'c1\'|\'c2\', array{1}|array{4}>', $cData);
};
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ public function testBug7000b(): void
{
$this->analyse([__DIR__ . '/data/bug-7000b.php'], [
[
"Offset 'require'|'require-dev' might not exist on array{require?: array<string, string>, require-dev?: array<string, string>}.",
"Offset 'require'|'require-dev' might not exist on non-empty-array{require?: array<string, string>, require-dev?: array<string, string>}.",
16,
],
]);
Expand Down
Loading