ClassExtractor   A
last analyzed

Complexity

Total Complexity 16

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
eloc 30
c 1
b 0
f 0
dl 0
loc 74
ccs 36
cts 36
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A isToken() 0 3 2
B __invoke() 0 23 7
A isNextToken() 0 5 1
A nextToken() 0 7 2
A __construct() 0 3 1
A extractNamespace() 0 9 2
A extractClassName() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Borodulin\Finder;
6
7
use Borodulin\Finder\Exception\ParseException;
8
9
class ClassExtractor
10
{
11
    /**
12
     * @var bool
13
     */
14
    private $skipAbstract;
15
16 3
    public function __construct(bool $skipAbstract = true)
17
    {
18 3
        $this->skipAbstract = $skipAbstract;
19 3
    }
20
21 3
    public function __invoke($filename): ?string
22
    {
23 3
        $tokens = token_get_all(file_get_contents($filename));
24
25 3
        $namespace = '';
26
27 3
        $token = current($tokens);
28 3
        while (false !== $token) {
29 3
            if ($this->skipAbstract && $this->isToken($token, T_ABSTRACT)) {
30 2
                return null;
31
            }
32 3
            if ($this->isToken($token, T_NAMESPACE)) {
33 2
                $namespace = $this->extractNamespace($tokens);
34
            }
35 3
            if ($this->isToken($token, T_CLASS)) {
36 3
                $className = $this->extractClassName($tokens);
37
38 2
                return $namespace ? "$namespace\\$className" : $className;
39
            }
40 3
            $token = next($tokens);
41
        }
42
43 2
        return null;
44
    }
45
46 3
    private function isToken($token, int $tokenType): bool
47
    {
48 3
        return \is_array($token) && $token[0] === $tokenType;
49
    }
50
51 3
    private function nextToken(array &$tokens, int $tokenType): string
52
    {
53 3
        $token = next($tokens);
54 3
        if (($token[0] ?? null) === $tokenType) {
55 2
            return $token[1];
56
        }
57 2
        throw new ParseException('Parse error. Expected '.token_name($tokenType));
58
    }
59
60 2
    private function isNextToken(array &$tokens, int $tokenType): bool
61
    {
62 2
        $token = next($tokens);
63
64 2
        return $this->isToken($token, $tokenType);
65
    }
66
67 2
    private function extractNamespace(array &$tokens): string
68
    {
69 2
        $this->nextToken($tokens, T_WHITESPACE);
70 2
        $namespace = $this->nextToken($tokens, T_STRING);
71 2
        while ($this->isNextToken($tokens, T_NS_SEPARATOR)) {
72 2
            $namespace .= '\\'.$this->nextToken($tokens, T_STRING);
73
        }
74
75 2
        return $namespace;
76
    }
77
78 3
    private function extractClassName(array &$tokens): string
79
    {
80 3
        $this->nextToken($tokens, T_WHITESPACE);
81
82 2
        return $this->nextToken($tokens, T_STRING);
83
    }
84
}
85