cookiebot
/
addons
/
lib
/
ioc
/
php-di
/
phpdoc-reader
/
src
/
PhpDocReader
/
PhpParser
/
UseStatementParser.php
cookiebot
/
addons
/
lib
/
ioc
/
php-di
/
phpdoc-reader
/
src
/
PhpDocReader
/
PhpParser
Last commit date
TokenParser.php
7 years ago
UseStatementParser.php
7 years ago
UseStatementParser.php
69 lines
| 1 | <?php |
| 2 | |
| 3 | namespace PhpDocReader\PhpParser; |
| 4 | |
| 5 | use SplFileObject; |
| 6 | |
| 7 | /** |
| 8 | * Parses a file for "use" declarations. |
| 9 | * |
| 10 | * Class taken and adapted from doctrine/annotations to avoid pulling the whole package. |
| 11 | * |
| 12 | * @author Fabien Potencier <fabien@symfony.com> |
| 13 | * @author 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) |
| 21 | { |
| 22 | if (false === $filename = $class->getFilename()) { |
| 23 | return array(); |
| 24 | } |
| 25 | |
| 26 | $content = $this->getFileContent($filename, $class->getStartLine()); |
| 27 | |
| 28 | if (null === $content) { |
| 29 | return array(); |
| 30 | } |
| 31 | |
| 32 | $namespace = preg_quote($class->getNamespaceName()); |
| 33 | $content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content); |
| 34 | $tokenizer = new TokenParser('<?php ' . $content); |
| 35 | |
| 36 | $statements = $tokenizer->parseUseStatements($class->getNamespaceName()); |
| 37 | |
| 38 | return $statements; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Gets the content of the file right up to the given line number. |
| 43 | * |
| 44 | * @param string $filename The name of the file to load. |
| 45 | * @param integer $lineNumber The number of lines to read from file. |
| 46 | * |
| 47 | * @return string The content of the file. |
| 48 | */ |
| 49 | private function getFileContent($filename, $lineNumber) |
| 50 | { |
| 51 | if ( ! is_file($filename)) { |
| 52 | return null; |
| 53 | } |
| 54 | |
| 55 | $content = ''; |
| 56 | $lineCnt = 0; |
| 57 | $file = new SplFileObject($filename); |
| 58 | while (!$file->eof()) { |
| 59 | if ($lineCnt++ == $lineNumber) { |
| 60 | break; |
| 61 | } |
| 62 | |
| 63 | $content .= $file->fgets(); |
| 64 | } |
| 65 | |
| 66 | return $content; |
| 67 | } |
| 68 | } |
| 69 |