Skip to content

Discover repository class from #[Entity] attribute on PHP 8 #238

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions attribute-errors.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
parameters:
ignoreErrors:
-
message: "#^Call to an undefined method ReflectionClass::getAttributes\\(\\)\\.$#"
count: 1
path: src/Type/Doctrine/ObjectMetadataResolver.php
15 changes: 15 additions & 0 deletions ignore-by-php-version.neon.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php declare(strict_types = 1);

use PHPStan\DependencyInjection\NeonAdapter;

$adapter = new NeonAdapter();

$config = [];

if (PHP_VERSION_ID < 80000) {
$config = array_merge_recursive($config, $adapter->load(__DIR__ . '/attribute-errors.neon'));
}

$config['parameters']['phpVersion'] = PHP_VERSION_ID;

return $config;
1 change: 1 addition & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
includes:
- extension.neon
- rules.neon
- ignore-by-php-version.neon.php
- vendor/phpstan/phpstan-strict-rules/rules.neon
- vendor/phpstan/phpstan-phpunit/extension.neon
- vendor/phpstan/phpstan-phpunit/rules.neon
Expand Down
12 changes: 12 additions & 0 deletions src/Type/Doctrine/ObjectMetadataResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace PHPStan\Type\Doctrine;

use Doctrine\ORM\Mapping\Entity;
use Doctrine\Persistence\ObjectManager;
use PHPStan\Reflection\ReflectionProvider;
use function is_file;
Expand Down Expand Up @@ -97,6 +98,17 @@ public function getResolvedRepositoryClass(): string

public function getRepositoryClass(string $className): string
{
if (PHP_MAJOR_VERSION >= 8 && $this->reflectionProvider->hasClass($className)) {
$classReflection = $this->reflectionProvider->getClass($className)->getNativeReflection();
$attribute = $classReflection->getAttributes(Entity::class)[0] ?? null;
if ($attribute !== null) {
$attributeInstance = $attribute->newInstance();
if ($attributeInstance->repositoryClass !== null) {
return $attributeInstance->repositoryClass;
}
}
}

$objectManager = $this->getObjectManager();
if ($objectManager === null) {
return $this->getResolvedRepositoryClass();
Expand Down