Skip to content

Commit 5eea5cb

Browse files
get_defined_vars() return type contains know variables
1 parent 71d01d6 commit 5eea5cb

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

conf/config.neon

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1427,6 +1427,11 @@ services:
14271427
tags:
14281428
- phpstan.broker.dynamicFunctionReturnTypeExtension
14291429

1430+
-
1431+
class: PHPStan\Type\Php\GetDefinedVarsFunctionReturnTypeExtension
1432+
tags:
1433+
- phpstan.broker.dynamicFunctionReturnTypeExtension
1434+
14301435
-
14311436
class: PHPStan\Type\Php\GetParentClassDynamicFunctionReturnTypeExtension
14321437
tags:
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
<?php declare(strict_types = 1);
2+
3+
namespace PHPStan\Type\Php;
4+
5+
use PhpParser\Node\Expr\FuncCall;
6+
use PHPStan\Analyser\Scope;
7+
use PHPStan\Reflection\FunctionReflection;
8+
use PHPStan\Type\ArrayType;
9+
use PHPStan\Type\Constant\ConstantArrayType;
10+
use PHPStan\Type\Constant\ConstantStringType;
11+
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
12+
use PHPStan\Type\MixedType;
13+
use PHPStan\Type\StringType;
14+
use PHPStan\Type\Type;
15+
use function array_filter;
16+
use function array_map;
17+
use function array_values;
18+
19+
// based on code by @ruudk
20+
final class GetDefinedVarsFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
21+
{
22+
23+
public function isFunctionSupported(FunctionReflection $functionReflection): bool
24+
{
25+
return $functionReflection->getName() === 'get_defined_vars';
26+
}
27+
28+
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
29+
{
30+
if ($scope->canAnyVariableExist()) {
31+
return new ArrayType(
32+
new StringType(),
33+
new MixedType(),
34+
);
35+
}
36+
37+
$variables = array_values(array_filter(
38+
$scope->getDefinedVariables(),
39+
static fn ($variable) => $variable !== 'this',
40+
));
41+
42+
$keys = array_map(
43+
static fn ($variable) => new ConstantStringType($variable),
44+
$variables,
45+
);
46+
47+
$values = array_map(
48+
static fn ($variable) => $scope->getVariableType($variable),
49+
$variables,
50+
);
51+
52+
return new ConstantArrayType($keys, $values);
53+
}
54+
55+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace GetDefinedVars;
4+
5+
use function PHPStan\Testing\assertType;
6+
7+
function doFoo(int $param) {
8+
$local = "foo";
9+
assertType('array{param: int, local: \'foo\'}', get_defined_vars());
10+
assertType('array{\'param\', \'local\'}', array_keys(get_defined_vars()));
11+
}

0 commit comments

Comments
 (0)