| 1 |
<?php declare(strict_types=1); |
| 2 |
// phpcs:ignoreFile -- Bundled third-party (Mozart) dependency; exempt from plugin coding standards. |
| 3 |
|
| 4 |
namespace WPDeveloper\BetterDocs\Dependencies\PhpDocReader\PhpParser; |
| 5 |
|
| 6 |
use SplFileObject; |
| 7 |
|
| 8 |
/** |
| 9 |
* Parses a file for "use" declarations. |
| 10 |
* |
| 11 |
* Class taken and adapted from doctrine/annotations to avoid pulling the whole package. |
| 12 |
* |
| 13 |
* Authors: Fabien Potencier <fabien@symfony.com> and Christian Kaps <christian.kaps@mohiva.com> |
| 14 |
*/ |
| 15 |
class UseStatementParser |
| 16 |
{ |
| 17 |
/** |
| 18 |
* @return array A list with use statements in the form (Alias => FQN). |
| 19 |
*/ |
| 20 |
public function parseUseStatements(\ReflectionClass $class): array |
| 21 |
{ |
| 22 |
$filename = $class->getFilename(); |
| 23 |
if ($filename === false) { |
| 24 |
return []; |
| 25 |
} |
| 26 |
|
| 27 |
$content = $this->getFileContent($filename, $class->getStartLine()); |
| 28 |
|
| 29 |
if ($content === null) { |
| 30 |
return []; |
| 31 |
} |
| 32 |
|
| 33 |
$namespace = preg_quote($class->getNamespaceName(), '/'); |
| 34 |
$content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content); |
| 35 |
$tokenizer = new TokenParser('<?php ' . $content); |
| 36 |
|
| 37 |
return $tokenizer->parseUseStatements($class->getNamespaceName()); |
| 38 |
} |
| 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 |
private function getFileContent(string $filename, int $lineNumber): string |
| 47 |
{ |
| 48 |
if (! is_file($filename)) { |
| 49 |
throw new \RuntimeException("Unable to read file $filename"); |
| 50 |
} |
| 51 |
|
| 52 |
$content = ''; |
| 53 |
$lineCnt = 0; |
| 54 |
$file = new SplFileObject($filename); |
| 55 |
while (! $file->eof()) { |
| 56 |
if ($lineCnt++ === $lineNumber) { |
| 57 |
break; |
| 58 |
} |
| 59 |
|
| 60 |
$content .= $file->fgets(); |
| 61 |
} |
| 62 |
|
| 63 |
return $content; |
| 64 |
} |
| 65 |
} |
| 66 |
|