class PhpParser
Parses a file for namespaces/use/class declarations.
Hierarchy
- class \Doctrine\Common\Annotations\PhpParser
Expanded class hierarchy of PhpParser
File
-
vendor/
doctrine/ annotations/ lib/ Doctrine/ Common/ Annotations/ PhpParser.php, line 17
Namespace
Doctrine\Common\AnnotationsView source
final class PhpParser {
/**
* Parse a class or function for use statements.
*
* @param ReflectionClass|ReflectionFunction $reflection
*
* @psalm-return array<string, string> a list with use statements in the form (Alias => FQN).
*/
public function parseUseStatements($reflection) : array {
if (method_exists($reflection, 'getUseStatements')) {
return $reflection->getUseStatements();
}
$filename = $reflection->getFileName();
if ($filename === false) {
return [];
}
$content = $this->getFileContent($filename, $reflection->getStartLine());
if ($content === null) {
return [];
}
$namespace = preg_quote($reflection->getNamespaceName());
$content = preg_replace('/^.*?(\\bnamespace\\s+' . $namespace . '\\s*[;{].*)$/s', '\\1', $content);
$tokenizer = new TokenParser('<?php ' . $content);
return $tokenizer->parseUseStatements($reflection->getNamespaceName());
}
/**
* Gets the content of the file right up to the given line number.
*
* @param string $filename The name of the file to load.
* @param int $lineNumber The number of lines to read from file.
*
* @return string|null The content of the file or null if the file does not exist.
*/
private function getFileContent(string $filename, $lineNumber) {
if (!is_file($filename)) {
return null;
}
$content = '';
$lineCnt = 0;
$file = new SplFileObject($filename);
while (!$file->eof()) {
if ($lineCnt++ === $lineNumber) {
break;
}
$content .= $file->fgets();
}
return $content;
}
}
Members
Title Sort descending | Modifiers | Object type | Summary |
---|---|---|---|
PhpParser::getFileContent | private | function | Gets the content of the file right up to the given line number. |
PhpParser::parseUseStatements | public | function | Parse a class or function for use statements. |