Skip to content

Commit 22f9661

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.
1 parent 9f40e7f commit 22f9661

File tree

4 files changed

+34
-0
lines changed

4 files changed

+34
-0
lines changed

attribute-errors.neon

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
parameters:
2+
ignoreErrors:
3+
-
4+
message: "#^Call to an undefined method ReflectionClass::getAttributes\\(\\)\\.$#"
5+
count: 1
6+
path: src/Type/Doctrine/ObjectMetadataResolver.php

ignore-by-php-version.neon.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php declare(strict_types = 1);
2+
3+
use PHPStan\DependencyInjection\NeonAdapter;
4+
5+
$adapter = new NeonAdapter();
6+
7+
$config = [];
8+
9+
if (PHP_VERSION_ID < 80000) {
10+
$config = array_merge_recursive($config, $adapter->load(__DIR__ . '/attribute-errors.neon'));
11+
}
12+
13+
$config['parameters']['phpVersion'] = PHP_VERSION_ID;
14+
15+
return $config;

phpstan.neon

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
includes:
22
- extension.neon
33
- rules.neon
4+
- ignore-by-php-version.neon.php
45
- vendor/phpstan/phpstan-strict-rules/rules.neon
56
- vendor/phpstan/phpstan-phpunit/extension.neon
67
- vendor/phpstan/phpstan-phpunit/rules.neon

src/Type/Doctrine/ObjectMetadataResolver.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace PHPStan\Type\Doctrine;
44

5+
use Doctrine\ORM\Mapping\Entity;
56
use Doctrine\Persistence\ObjectManager;
67
use PHPStan\Reflection\ReflectionProvider;
78
use function is_file;
@@ -97,6 +98,17 @@ public function getResolvedRepositoryClass(): string
9798

9899
public function getRepositoryClass(string $className): string
99100
{
101+
if (PHP_MAJOR_VERSION >= 8 && $this->reflectionProvider->hasClass($className)) {
102+
$classReflection = $this->reflectionProvider->getClass($className)->getNativeReflection();
103+
$attribute = $classReflection->getAttributes(Entity::class)[0] ?? null;
104+
if ($attribute !== null) {
105+
$attributeInstance = $attribute->newInstance();
106+
if ($attributeInstance->repositoryClass !== null) {
107+
return $attributeInstance->repositoryClass;
108+
}
109+
}
110+
}
111+
100112
$objectManager = $this->getObjectManager();
101113
if ($objectManager === null) {
102114
return $this->getResolvedRepositoryClass();

0 commit comments

Comments
 (0)