Skip to content

Commit 0bd65db

Browse files
get_defined_vars() return type contains know variables
1 parent 71d01d6 commit 0bd65db

File tree

3 files changed

+68
-0
lines changed

3 files changed

+68
-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: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
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+
16+
// based on code by @ruudk
17+
final class GetDefinedVarsFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
18+
{
19+
20+
public function isFunctionSupported(FunctionReflection $functionReflection): bool
21+
{
22+
return $functionReflection->getName() === 'get_defined_vars';
23+
}
24+
25+
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
26+
{
27+
if ($scope->canAnyVariableExist()) {
28+
return new ArrayType(
29+
new StringType(),
30+
new MixedType(),
31+
);
32+
}
33+
34+
$variables = \array_values(\array_filter(
35+
$scope->getDefinedVariables(),
36+
static fn ($variable) => $variable !== 'this',
37+
));
38+
39+
$keys = \array_map(
40+
static fn ($variable) => new ConstantStringType($variable),
41+
$variables,
42+
);
43+
44+
$values = \array_map(
45+
static fn ($variable) => $scope->getVariableType($variable),
46+
$variables,
47+
);
48+
49+
return new ConstantArrayType($keys, $values);
50+
}
51+
52+
}
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)