PhpParser::getFileContent()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 18
rs 9.9332
c 0
b 0
f 0
cc 4
nc 4
nop 2
1
<?php
2
3
namespace Doctrine\Common\Annotations;
4
5
use SplFileObject;
6
7
/**
8
 * Parses a file for namespaces/use/class declarations.
9
 *
10
 * @author Fabien Potencier <[email protected]>
11
 * @author Christian Kaps <[email protected]>
12
 */
13
final class PhpParser
14
{
15
    /**
16
     * Parses a class.
17
     *
18
     * @param \ReflectionClass $class A <code>ReflectionClass</code> object.
19
     *
20
     * @return array A list with use statements in the form (Alias => FQN).
21
     */
22
    public function parseClass(\ReflectionClass $class)
23
    {
24
        if (method_exists($class, 'getUseStatements')) {
25
            return $class->getUseStatements();
26
        }
27
28
        if (false === $filename = $class->getFileName()) {
29
            return [];
30
        }
31
32
        $content = $this->getFileContent($filename, $class->getStartLine());
33
34
        if (null === $content) {
35
            return [];
36
        }
37
38
        $namespace = preg_quote($class->getNamespaceName());
39
        $content = preg_replace('/^.*?(\bnamespace\s+' . $namespace . '\s*[;{].*)$/s', '\\1', $content);
40
        $tokenizer = new TokenParser('<?php ' . $content);
41
42
        $statements = $tokenizer->parseUseStatements($class->getNamespaceName());
43
44
        return $statements;
45
    }
46
47
    /**
48
     * Gets the content of the file right up to the given line number.
49
     *
50
     * @param string  $filename   The name of the file to load.
51
     * @param integer $lineNumber The number of lines to read from file.
52
     *
53
     * @return string|null The content of the file or null if the file does not exist.
54
     */
55
    private function getFileContent($filename, $lineNumber)
56
    {
57
        if ( ! is_file($filename)) {
58
            return null;
59
        }
60
61
        $content = '';
62
        $lineCnt = 0;
63
        $file = new SplFileObject($filename);
64
        while (!$file->eof()) {
65
            if ($lineCnt++ == $lineNumber) {
66
                break;
67
            }
68
69
            $content .= $file->fgets();
70
        }
71
72
        return $content;
73
    }
74
}
75