|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Symplify\PHPStanRules\Doctrine; |
| 6 | + |
| 7 | +use Nette\Utils\FileSystem; |
| 8 | +use Nette\Utils\Strings; |
| 9 | +use PHPStan\Reflection\ReflectionProvider; |
| 10 | +use Rector\Exception\ShouldNotHappenException; |
| 11 | + |
| 12 | +final readonly class RepositoryClassResolver |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @var string |
| 16 | + */ |
| 17 | + private const QUOTED_REPOSITORY_CLASS_REGEX = '#repositoryClass=\"(?<repositoryClass>.*?)\"#'; |
| 18 | + |
| 19 | + /** |
| 20 | + * @var string |
| 21 | + */ |
| 22 | + private const USE_REPOSITORY_REGEX = '#use (?<repositoryClass>.*?Repository);#'; |
| 23 | + |
| 24 | + public function __construct( |
| 25 | + private ReflectionProvider $reflectionProvider |
| 26 | + ) { |
| 27 | + } |
| 28 | + |
| 29 | + public function resolveFromEntityClass(string $entityClassName): ?string |
| 30 | + { |
| 31 | + if (! $this->reflectionProvider->hasClass($entityClassName)) { |
| 32 | + throw new ShouldNotHappenException(); |
| 33 | + } |
| 34 | + |
| 35 | + $classReflection = $this->reflectionProvider->getClass($entityClassName); |
| 36 | + |
| 37 | + $entityClassFileName = $classReflection->getFileName(); |
| 38 | + if ($entityClassFileName === null) { |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + $entityFileContents = FileSystem::read($entityClassFileName); |
| 43 | + |
| 44 | + // match repositoryClass="..." in entity |
| 45 | + $match = Strings::match($entityFileContents, self::QUOTED_REPOSITORY_CLASS_REGEX); |
| 46 | + |
| 47 | + if (! isset($match['repositoryClass'])) { |
| 48 | + // try fallback to repository ::class + use import |
| 49 | + |
| 50 | + $repositoryUseMatch = Strings::match($entityFileContents, self::USE_REPOSITORY_REGEX); |
| 51 | + if (isset($repositoryUseMatch['repositoryClass'])) { |
| 52 | + $repositoryClass = $repositoryUseMatch['repositoryClass']; |
| 53 | + } else { |
| 54 | + // unable to resolve |
| 55 | + return null; |
| 56 | + } |
| 57 | + } else { |
| 58 | + $repositoryClass = $match['repositoryClass']; |
| 59 | + } |
| 60 | + |
| 61 | + if (! $this->reflectionProvider->hasClass($repositoryClass)) { |
| 62 | + throw new ShouldNotHappenException( |
| 63 | + sprintf('Repository class "%s" for entity "%s" does not exist', $repositoryClass, $entityClassName) |
| 64 | + ); |
| 65 | + } |
| 66 | + |
| 67 | + return $repositoryClass; |
| 68 | + } |
| 69 | +} |
0 commit comments