From 750d18d20ab859295b012fa670397f692c21feec Mon Sep 17 00:00:00 2001 From: Matt Brown Date: Tue, 7 Nov 2017 17:38:54 -0500 Subject: [PATCH] Fix #266 - do better analysis of array_rand And also have better fallback when accessing string key on object-like array --- .../Checker/Statements/Expression/FetchChecker.php | 2 ++ src/Psalm/Stubs/CoreGenericFunctions.php | 8 ++++++++ tests/FunctionCallTest.php | 12 ++++++++++++ 3 files changed, 22 insertions(+) diff --git a/src/Psalm/Checker/Statements/Expression/FetchChecker.php b/src/Psalm/Checker/Statements/Expression/FetchChecker.php index 6f63a6bbb..fdf2afefb 100644 --- a/src/Psalm/Checker/Statements/Expression/FetchChecker.php +++ b/src/Psalm/Checker/Statements/Expression/FetchChecker.php @@ -1130,6 +1130,8 @@ class FetchChecker )) { return false; } + } elseif ($key_type->hasString()) { + $stmt->inferredType = $type->getGenericTypeParam(); } } continue; diff --git a/src/Psalm/Stubs/CoreGenericFunctions.php b/src/Psalm/Stubs/CoreGenericFunctions.php index e76a07182..44b5dcdc6 100644 --- a/src/Psalm/Stubs/CoreGenericFunctions.php +++ b/src/Psalm/Stubs/CoreGenericFunctions.php @@ -107,3 +107,11 @@ function array_pop(array $arr) {} * @return array */ function array_reverse(array $arr) {} + +/** + * @template TKey + * + * @param array $arr + * @return TKey + */ +function array_rand(array $arr) {} diff --git a/tests/FunctionCallTest.php b/tests/FunctionCallTest.php index 7affbc8d8..d8e78b300 100644 --- a/tests/FunctionCallTest.php +++ b/tests/FunctionCallTest.php @@ -281,6 +281,18 @@ class FunctionCallTest extends TestCase fooFoo($a->foo); fooFoo($b);', ], + 'arrayRand' => [ + ' "a", "y" => "b"]; + $c = array_rand($vars); + $d = $vars[$c];', + + 'assertions' => [ + '$vars' => 'array{x:string, y:string}', + '$c' => 'string', + '$d' => 'string', + ], + ], ]; }