Completed
Push — master ( 6c80b5...e40af7 )
by Nikola
03:03
created

Tokenizer::findClass()   D

Complexity

Conditions 18
Paths 101

Size

Total Lines 45
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 342

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 45
ccs 0
cts 35
cp 0
rs 4.932
cc 18
eloc 24
nc 101
nop 1
crap 342

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace RunOpenCode\AbstractBuilder\Helper;
4
5
use RunOpenCode\AbstractBuilder\Exception\RuntimeException;
6
7
class Tokenizer
8
{
9
    public static function findClass($path)
10
    {
11
        if (!file_exists($path) || !is_file($path)) {
12
            throw new RuntimeException(sprintf('There is no file on path "%s".', $path));
13
        }
14
15
        if (!is_readable($path)) {
16
            throw new RuntimeException(sprintf('There is a file on path "%s", but it is not readable.', $path));
17
        }
18
19
        $contents = file_get_contents($path);
20
        $namespace = $class = '';
21
        $getting_namespace = $getting_class = false;
22
23
        foreach (token_get_all($contents) as $token) {
24
25
            if (is_array($token) && $token[0] === T_NAMESPACE) {
26
                $getting_namespace = true;
27
            }
28
29
            if (is_array($token) && $token[0] === T_CLASS) {
30
                $getting_class = true;
31
            }
32
33
            if ($getting_namespace === true) {
34
35
                if(is_array($token) && in_array($token[0], [T_STRING, T_NS_SEPARATOR], true)) {
36
                    $namespace .= $token[1];
37
                } elseif ($token === ';') {
38
                    $getting_namespace = false;
39
                }
40
            }
41
42
            if ($getting_class === true && is_array($token) && $token[0] === T_STRING) {
43
                $class = $token[1];
44
                break;
45
            }
46
        }
47
48
        if ('' === $namespace.$class) {
49
            throw new RuntimeException(sprintf('There is no class definition in file on path "%s".', $path));
50
        }
51
52
        return $namespace ? $namespace . '\\' . $class : $class;
53
    }
54
}
55