No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

NameScopeFactory.php 2.2KB

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