Skip to content
Closed
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
12 changes: 12 additions & 0 deletions src/Type/Php/ArrayReverseFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\Accessory\NonEmptyArrayType;
use PHPStan\Type\ArrayType;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
Expand Down Expand Up @@ -43,6 +45,16 @@ public function getTypeFromFunctionCall(FunctionReflection $functionReflection,
return TypeCombinator::union(...$results);
}

if ($preserveKeys) {
// Remove list
$newArrayType = new ArrayType($type->getIterableKeyType(), $type->getIterableValueType());
if ($type->isIterableAtLeastOnce()->yes()) {
$newArrayType = TypeCombinator::intersect($newArrayType, new NonEmptyArrayType());
}

return $newArrayType;
Comment on lines +49 to +55
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

An almost identical construct exists already somewhere. And I might add it another time somewhere else. I was wondering if it makes sense to re-use this somehow somewhere..

Copy link
Contributor Author

@herndlm herndlm Aug 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the cleaner alternative of course would be a refactor that moves reverse() to Type (arrayReverse()?). The more I think about it, the more I like it 😊

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, moving this to type fixes like at least 3 other edge cases as well....

}

return $type;
}

Expand Down
13 changes: 13 additions & 0 deletions tests/PHPStan/Analyser/nsrt/array-reverse.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,17 @@ public function constantArrays(array $a, array $b): void
assertType('array{\'bar\', \'foo\'}|array{bar: 19, foo: 17}', array_reverse($b));
assertType('array{19: \'bar\', 17: \'foo\'}|array{bar: 19, foo: 17}', array_reverse($b, true));
}

/**
* @param list<string> $a
* @param non-empty-list<string> $b
*/
public function list(array $a, array $b): void
{
assertType('list<string>', array_reverse($a));
assertType('array<int<0, max>, string>', array_reverse($a, true));

assertType('non-empty-list<string>', array_reverse($b));
assertType('non-empty-array<int<0, max>, string>', array_reverse($b, true));
}
}
Loading