Skip to content

Commit 7af0c4e

Browse files
committed
Cache constant reflections
1 parent 5f7c3d6 commit 7af0c4e

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/Reflection/BetterReflection/BetterReflectionProvider.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,9 @@ class BetterReflectionProvider implements ReflectionProvider
8282
/** @var \PHPStan\Reflection\ClassReflection[] */
8383
private static array $anonymousClasses = [];
8484

85+
/** @var array<string, GlobalConstantReflection> */
86+
private array $cachedConstants = [];
87+
8588
public function __construct(
8689
ReflectionProvider\ReflectionProviderProvider $reflectionProviderProvider,
8790
ClassReflectionExtensionRegistryProvider $classReflectionExtensionRegistryProvider,
@@ -359,6 +362,10 @@ public function getConstant(\PhpParser\Node\Name $nameNode, ?Scope $scope): Glob
359362
throw new \PHPStan\Broker\ConstantNotFoundException((string) $nameNode);
360363
}
361364

365+
if (array_key_exists($constantName, $this->cachedConstants)) {
366+
return $this->cachedConstants[$constantName];
367+
}
368+
362369
$constantReflection = $this->constantReflector->reflect($constantName);
363370
try {
364371
$constantValue = $constantReflection->getValue();
@@ -369,7 +376,7 @@ public function getConstant(\PhpParser\Node\Name $nameNode, ?Scope $scope): Glob
369376
$fileName = null;
370377
}
371378

372-
return new RuntimeConstantReflection(
379+
return $this->cachedConstants[$constantName] = new RuntimeConstantReflection(
373380
$constantName,
374381
$constantValueType,
375382
$fileName

src/Reflection/Runtime/RuntimeReflectionProvider.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,9 @@ class RuntimeReflectionProvider implements ReflectionProvider
5959
/** @var \PHPStan\Reflection\ClassReflection[] */
6060
private static array $anonymousClasses = [];
6161

62+
/** @var array<string, GlobalConstantReflection> */
63+
private array $cachedConstants = [];
64+
6265
public function __construct(
6366
ReflectionProvider\ReflectionProviderProvider $reflectionProviderProvider,
6467
ClassReflectionExtensionRegistryProvider $classReflectionExtensionRegistryProvider,
@@ -341,7 +344,11 @@ public function getConstant(\PhpParser\Node\Name $nameNode, ?Scope $scope): Glob
341344
throw new \PHPStan\Broker\ConstantNotFoundException((string) $nameNode);
342345
}
343346

344-
return new RuntimeConstantReflection(
347+
if (array_key_exists($constantName, $this->cachedConstants)) {
348+
return $this->cachedConstants[$constantName];
349+
}
350+
351+
return $this->cachedConstants[$constantName] = new RuntimeConstantReflection(
345352
$constantName,
346353
ConstantTypeHelper::getTypeFromValue(constant($constantName)),
347354
null

0 commit comments

Comments
 (0)