Skip to content

Commit

Permalink
Simplify some more
Browse files Browse the repository at this point in the history
  • Loading branch information
herndlm committed Jan 5, 2025
1 parent 75e06bd commit 77c0c0c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 11 deletions.
19 changes: 8 additions & 11 deletions src/Type/Php/ArrayMergeFunctionDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,40 +40,37 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,

$argTypes = [];
$optionalArgTypes = [];
$allConstant = TrinaryLogic::createYes();
foreach ($args as $arg) {
$argType = $scope->getType($arg->value);

if ($arg->unpack) {
if ($argType->isConstantArray()->yes()) {
$argTypesFound = [];
foreach ($argType->getConstantArrays() as $constantArray) {
foreach ($constantArray->getValueTypes() as $valueType) {
$argTypesFound[] = $valueType;
$argTypes[] = $valueType;
}
}
} else {
$argTypesFound = [$argType->getIterableValueType()];
}

foreach ($argTypesFound as $argTypeFound) {
$argTypes[] = $argTypeFound;
$allConstant = $allConstant->and($argTypeFound->isConstantArray());
$argTypes[] = $argType->getIterableValueType();
}

if (!$argType->isIterableAtLeastOnce()->yes()) {
// unpacked params can be empty, making them optional
$optionalArgTypesOffset = count($argTypes) - 1;
foreach (array_keys($argTypesFound) as $key) {
foreach (array_keys($argTypes) as $key) {
$optionalArgTypes[] = $optionalArgTypesOffset + $key;
}
}
} else {
$argTypes[] = $argType;
$allConstant = $allConstant->and($argType->isConstantArray());
}
}

$allConstant = TrinaryLogic::createYes()->lazyAnd(
$argTypes,
static fn (Type $argType) => $argType->isConstantArray(),
);

if ($allConstant->yes()) {
$newArrayBuilder = ConstantArrayTypeBuilder::createEmpty();
foreach ($argTypes as $argType) {
Expand Down
2 changes: 2 additions & 0 deletions tests/PHPStan/Analyser/nsrt/array-merge2.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ public function arrayMergeArrayShapes($array1, $array2): void
assertType("array{foo: 3, bar: '2', lall2: '3', 0: '4', 1: '6', lall: '3', 2: '2', 3: '3'}", array_merge($array2, $array1, ...[['foo' => 3]]));
assertType("array{foo: '1', bar: '2'|'4', lall?: '3', 0: '2'|'4', 1: '3'|'6', lall2?: '3'}", array_merge(rand(0, 1) ? $array1 : $array2, []));
assertType("array{foo?: 3, bar?: 3}", array_merge([], ...[rand(0, 1) ? ['foo' => 3] : ['bar' => 3]]));
assertType("array{foo: '1', bar: '2'|'4', lall?: '3', 0: '2'|'4', 1: '3'|'6', lall2?: '3'}", array_merge([], ...[rand(0, 1) ? $array1 : $array2]));
assertType("array{foo: 1, bar: 2, 0: 2, 1: 3}", array_merge(['foo' => 4, 'bar' => 5], ...[['foo' => 1, 'bar' => 2], [2, 3]]));
}

/**
Expand Down

0 comments on commit 77c0c0c

Please sign in to comment.