DependenciesReader::findFileDependencies()   B
last analyzed

Complexity

Conditions 6
Paths 24

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
c 0
b 0
f 0
rs 8.5125
cc 6
eloc 15
nc 24
nop 1
1
<?php
2
/**
3
 * @copyright 2018 Aleksander Stelmaczonek <[email protected]>
4
 * @license   MIT License, see license file distributed with this source code
5
 */
6
7
namespace Koriit\PHPDeps\Tokenizer;
8
9
use Koriit\PHPDeps\Tokenizer\Exceptions\MalformedFile;
10
use Koriit\PHPDeps\Tokenizer\Exceptions\UnexpectedEndOfTokens;
11
use Koriit\PHPDeps\Tokenizer\Exceptions\UnexpectedToken;
12
use Koriit\PHPDeps\Tokenizer\Exceptions\WrongPosition;
13
14
class DependenciesReader
15
{
16
    /**
17
     * @param string $filePath Path to file to parse
18
     *
19
     * @throws MalformedFile
20
     *
21
     * @return string[] Real dependencies read from use statements
22
     */
23
    public function findFileDependencies($filePath)
24
    {
25
        $tokens = TokensIterator::fromFile($filePath);
26
27
        $useDependencies = [];
28
29
        try {
30
            while ($tokens->valid()) {
31
                if ($tokens->currentIsOneOf([T_CLASS, T_TRAIT, T_FUNCTION, T_INTERFACE])) {
32
                    $tokens->skipNextBlock();
33
                } elseif ($tokens->currentIs(T_USE)) {
34
                    $useDependencies[] = $this->readUseStatement($tokens);
35
                }
36
37
                $tokens->next();
38
            }
39
        } catch (UnexpectedEndOfTokens $e) {
40
            throw new MalformedFile($filePath, $e);
41
        } catch (UnexpectedToken $e) {
42
            throw new MalformedFile($filePath, $e);
43
        }
44
45
        return $useDependencies;
46
    }
47
48
    /**
49
     * @param TokensIterator $it
50
     *
51
     * @throws UnexpectedEndOfTokens
52
     * @throws UnexpectedToken
53
     *
54
     * @return string Real dependency from use statement
55
     */
56
    private function readUseStatement(TokensIterator $it)
57
    {
58
        if (!$it->valid() || !$it->currentIs(T_USE)) {
59
            throw new WrongPosition('Not at use statement position.');
60
        }
61
62
        $it->skipTokensIfPresent([T_USE, T_WHITESPACE, T_CONST, T_FUNCTION]);
63
64
        $dependency = '';
65
        while ($it->valid()) {
66
            $token = $it->current();
67
            if ($token == ';' || $it->currentIs(T_AS)) {
68
                return $dependency;
69
            } elseif ($it->currentIsOneOf([T_STRING, T_NS_SEPARATOR])) {
70
                $dependency .= $token[1];
71
            } elseif (!$it->currentIs(T_WHITESPACE)) {
72
                throw new UnexpectedToken($token);
73
            }
74
75
            $it->next();
76
        }
77
78
        throw new UnexpectedEndOfTokens();
79
    }
80
}
81