NameScopeFactory.php
71 lines
| 1 | <?php |
| 2 | |
| 3 | /* |
| 4 | * This file is part of the Symfony package. |
| 5 | * |
| 6 | * (c) Fabien Potencier <fabien@symfony.com> |
| 7 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | */ |
| 11 | |
| 12 | namespace Symfony\Component\PropertyInfo\PhpStan; |
| 13 | |
| 14 | use phpDocumentor\Reflection\Types\ContextFactory; |
| 15 | |
| 16 | /** |
| 17 | * @author Baptiste Leduc <baptiste.leduc@gmail.com> |
| 18 | * |
| 19 | * @internal |
| 20 | */ |
| 21 | final class NameScopeFactory |
| 22 | { |
| 23 | public function create(string $calledClassName, ?string $declaringClassName = null): NameScope |
| 24 | { |
| 25 | $declaringClassName = $declaringClassName ?? $calledClassName; |
| 26 | |
| 27 | $path = explode('\\', $calledClassName); |
| 28 | $calledClassName = array_pop($path); |
| 29 | |
| 30 | $declaringReflection = new \ReflectionClass($declaringClassName); |
| 31 | [$declaringNamespace, $declaringUses] = $this->extractFromFullClassName($declaringReflection); |
| 32 | $declaringUses = array_merge($declaringUses, $this->collectUses($declaringReflection)); |
| 33 | |
| 34 | return new NameScope($calledClassName, $declaringNamespace, $declaringUses); |
| 35 | } |
| 36 | |
| 37 | private function collectUses(\ReflectionClass $reflection): array |
| 38 | { |
| 39 | $uses = [$this->extractFromFullClassName($reflection)[1]]; |
| 40 | |
| 41 | foreach ($reflection->getTraits() as $traitReflection) { |
| 42 | $uses[] = $this->extractFromFullClassName($traitReflection)[1]; |
| 43 | } |
| 44 | |
| 45 | if (false !== $parentClass = $reflection->getParentClass()) { |
| 46 | $uses[] = $this->collectUses($parentClass); |
| 47 | } |
| 48 | |
| 49 | return $uses ? array_merge(...$uses) : []; |
| 50 | } |
| 51 | |
| 52 | private function extractFromFullClassName(\ReflectionClass $reflection): array |
| 53 | { |
| 54 | $namespace = trim($reflection->getNamespaceName(), '\\'); |
| 55 | $fileName = $reflection->getFileName(); |
| 56 | |
| 57 | if (\is_string($fileName) && is_file($fileName)) { |
| 58 | if (false === $contents = file_get_contents($fileName)) { |
| 59 | throw new \RuntimeException(sprintf('Unable to read file "%s".', $fileName)); |
| 60 | } |
| 61 | |
| 62 | $factory = new ContextFactory(); |
| 63 | $context = $factory->createForNamespace($namespace, $contents); |
| 64 | |
| 65 | return [$namespace, $context->getNamespaceAliases()]; |
| 66 | } |
| 67 | |
| 68 | return [$namespace, []]; |
| 69 | } |
| 70 | } |
| 71 |