Completed
Push — master ( 1a0ee4...8fb63d )
by Andrey
02:06
created

ClassNameExtractor::extract()   A

Complexity

Conditions 6
Paths 8

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
c 2
b 0
f 0
nc 8
nop 1
dl 0
loc 23
ccs 14
cts 14
cp 1
crap 6
rs 9.2222
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Borodulin\Container\Autowire;
6
7
use Borodulin\Container\ContainerException;
8
9
class ClassNameExtractor
10
{
11 7
    public function extract($filename): ?string
12
    {
13 7
        $tokens = token_get_all(file_get_contents($filename));
14
15 7
        $namespace = '';
16
17 7
        $token = current($tokens);
18 7
        while (false !== $token) {
19 7
            if ($this->isToken($token, T_ABSTRACT)) {
20 5
                return null;
21
            }
22 7
            if ($this->isToken($token, T_NAMESPACE)) {
23 7
                $namespace = $this->extractNamespace($tokens);
24
            }
25 7
            if ($this->isToken($token, T_CLASS)) {
26 7
                $className = $this->extractClassName($tokens);
27
28 7
                return $namespace ? "$namespace\\$className" : $className;
29
            }
30 7
            $token = next($tokens);
31
        }
32
33 5
        return null;
34
    }
35
36 7
    private function isToken($token, int $tokenType): bool
37
    {
38 7
        return \is_array($token) && $token[0] === $tokenType;
39
    }
40
41 7
    private function nextToken(array &$tokens, int $tokenType): string
42
    {
43 7
        $token = next($tokens);
44 7
        if (($token[0] ?? null) === $tokenType) {
45 7
            return $token[1];
46
        }
47
        throw new ContainerException('Parse error. Expected '.token_name($tokenType));
48
    }
49
50 7
    private function isNextToken(array &$tokens, int $tokenType): bool
51
    {
52 7
        $token = next($tokens);
53
54 7
        return $this->isToken($token, $tokenType);
55
    }
56
57 7
    private function extractNamespace(array &$tokens): string
58
    {
59 7
        $this->nextToken($tokens, T_WHITESPACE);
60 7
        $namespace = $this->nextToken($tokens, T_STRING);
61 7
        while ($this->isNextToken($tokens, T_NS_SEPARATOR)) {
62 7
            $namespace .= '\\'.$this->nextToken($tokens, T_STRING);
63
        }
64
65 7
        return $namespace;
66
    }
67
68 7
    private function extractClassName(array &$tokens): string
69
    {
70 7
        $this->nextToken($tokens, T_WHITESPACE);
71
72 7
        return $this->nextToken($tokens, T_STRING);
73
    }
74
}
75