Skip to content

Commit 87e4bf7

Browse files
committed
Discover repository class from #[Entity] attribute on PHP 8
By doing it like this, we don't need to instantiate the object manager at all. Unfortunately, BetterReflection doesn't support attributes yet so therefore we need to use native `ReflectionClass`. See phpstan/phpstan#5863 (reply in thread)
1 parent 0625e90 commit 87e4bf7

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/Type/Doctrine/ObjectMetadataResolver.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@
22

33
namespace PHPStan\Type\Doctrine;
44

5+
use Doctrine\ORM\Mapping\Entity;
56
use Doctrine\Persistence\ObjectManager;
67
use PHPStan\Reflection\ReflectionProvider;
8+
use ReflectionClass;
79
use function is_file;
810
use function is_readable;
911

@@ -97,6 +99,17 @@ public function getResolvedRepositoryClass(): string
9799

98100
public function getRepositoryClass(string $className): string
99101
{
102+
if (PHP_MAJOR_VERSION >= 8 && $this->reflectionProvider->hasClass($className)) {
103+
/** @phpstan-var class-string $className */
104+
$reflector = new ReflectionClass($className);
105+
if (method_exists($reflector, 'getAttributes')) {
106+
$entityAttribute = $reflector->getAttributes(Entity::class)[0] ?? null;
107+
if ($entityAttribute !== null) {
108+
return $entityAttribute->newInstance()->repositoryClass;
109+
}
110+
}
111+
}
112+
100113
$objectManager = $this->getObjectManager();
101114
if ($objectManager === null) {
102115
return $this->getResolvedRepositoryClass();

0 commit comments

Comments
 (0)