PhpParser.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Doctrine\Common\Annotations;
  3. use ReflectionClass;
  4. use ReflectionFunction;
  5. use SplFileObject;
  6. use function is_file;
  7. use function method_exists;
  8. use function preg_quote;
  9. use function preg_replace;
  10. /**
  11. * Parses a file for namespaces/use/class declarations.
  12. */
  13. final class PhpParser
  14. {
  15. /**
  16. * Parse a class or function for use statements.
  17. *
  18. * @param ReflectionClass|ReflectionFunction $reflection
  19. *
  20. * @psalm-return array<string, string> a list with use statements in the form (Alias => FQN).
  21. */
  22. public function parseUseStatements($reflection): array
  23. {
  24. if (method_exists($reflection, 'getUseStatements')) {
  25. return $reflection->getUseStatements();
  26. }
  27. $filename = $reflection->getFileName();
  28. if ($filename === false) {
  29. return [];
  30. }
  31. $content = $this->getFileContent($filename, $reflection->getStartLine());
  32. if ($content === null) {
  33. return [];
  34. }
  35. $namespace = preg_quote($reflection->getNamespaceName());
  36. $content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content);
  37. $tokenizer = new TokenParser('<?php ' . $content);
  38. return $tokenizer->parseUseStatements($reflection->getNamespaceName());
  39. }
  40. /**
  41. * Gets the content of the file right up to the given line number.
  42. *
  43. * @param string $filename The name of the file to load.
  44. * @param int $lineNumber The number of lines to read from file.
  45. *
  46. * @return string|null The content of the file or null if the file does not exist.
  47. */
  48. private function getFileContent(string $filename, $lineNumber)
  49. {
  50. if (! is_file($filename)) {
  51. return null;
  52. }
  53. $content = '';
  54. $lineCnt = 0;
  55. $file = new SplFileObject($filename);
  56. while (! $file->eof()) {
  57. if ($lineCnt++ === $lineNumber) {
  58. break;
  59. }
  60. $content .= $file->fgets();
  61. }
  62. return $content;
  63. }
  64. }