Skip to content

Commit

Permalink
Improve check for empty array
Browse files Browse the repository at this point in the history
  • Loading branch information
muglug committed Jul 15, 2020
1 parent 0ab163f commit 06ee1b7
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 8 deletions.
15 changes: 9 additions & 6 deletions src/Psalm/Internal/Stubs/CoreGenericFunctions.phpstub
Expand Up @@ -132,10 +132,11 @@ function array_flip(array $arr)

/**
* @psalm-template TKey as array-key
* @psalm-template TArray as array<TKey, mixed>
*
* @param array<TKey, mixed> $arr
* @param TArray $arr
*
* @return (TKey is empty ? null : ($arr is non-empty-array ? TKey : TKey|null))
* @return (TArray is array<empty, empty> ? null : (TArray is non-empty-array ? TKey : TKey|null))
* @psalm-pure
*/
function key($arr)
Expand All @@ -144,10 +145,11 @@ function key($arr)

/**
* @psalm-template TKey as array-key
* @psalm-template TArray as array<TKey, mixed>
*
* @param array<TKey, mixed> $arr
* @param TArray $arr
*
* @return (TKey is empty ? null : ($arr is non-empty-array ? TKey : TKey|null))
* @return (TArray is array<empty, empty> ? null : (TArray is non-empty-array ? TKey : TKey|null))
* @psalm-pure
*/
function array_key_first($arr)
Expand All @@ -156,10 +158,11 @@ function array_key_first($arr)

/**
* @psalm-template TKey as array-key
* @psalm-template TArray as array<TKey, mixed>
*
* @param array<TKey, mixed> $arr
* @param TArray $arr
*
* @return (TKey is empty ? null : ($arr is non-empty-array ? TKey : TKey|null))
* @return (TArray is array<empty, empty> ? null : (TArray is non-empty-array ? TKey : TKey|null))
* @psalm-pure
*/
function array_key_last($arr)
Expand Down
10 changes: 10 additions & 0 deletions tests/ArrayFunctionCallTest.php
Expand Up @@ -770,6 +770,16 @@ function mapdef(string $_a, int $_b = 0): string {
'$b' => 'string',
],
],
'keyNonEmptyArray' => [
'<?php
/**
* @param non-empty-array $arr
* @return array-key
*/
function foo(array $arr) {
return key($arr);
}',
],
'arrayKeyFirst' => [
'<?php
/** @return array<string, int> */
Expand Down
3 changes: 1 addition & 2 deletions tests/TypeReconciliation/EmptyTest.php
Expand Up @@ -244,7 +244,7 @@ function foo(array $n): void {
}
}',
],
'SKIPPED-unsetChangesComplicatedArrayEmptiness' => [
'unsetChangesComplicatedArrayEmptiness' => [
'<?php
function contains(array $data, array $needle): bool {
if (empty($data) || empty($needle)) {
Expand All @@ -253,7 +253,6 @@ function contains(array $data, array $needle): bool {
$stack = [];
while (!empty($needle)) {
/** @psalm-trace $key */
$key = key($needle);
$val = $needle[$key];
unset($needle[$key]);
Expand Down

0 comments on commit 06ee1b7

Please sign in to comment.