ClassFileInfoTrait::detectInfo()   C
last analyzed

Complexity

Conditions 13
Paths 4

Size

Total Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 42
rs 6.6166
c 0
b 0
f 0
cc 13
nc 4
nop 1

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
 * ShouldPHP
4
 *
5
 * @author  Gabriel Jacinto <[email protected]>
6
 * @status  dev
7
 * @link    https://github.com/GabrielJMJ/ShouldPHP
8
 * @license MIT
9
 */
10
11
namespace Gabrieljmj\Should\Tool;
12
13
trait ClassFileInfoTrait
14
{
15
    protected $file;
16
17
    protected $class;
18
    protected $namespace;
19
20
    protected function getClass($file)
21
    {
22
        if ($this->class === null) {
23
            $this->detectInfo($file);
24
        }
25
26
        return $this->class;
27
    }
28
29
    protected function getNamespace($file)
30
    {
31
        if ($this->class === null) {
32
            $this->detectInfo($file);
33
        }
34
35
        return $this->namespace;
36
    }
37
38
    private function detectInfo($file)
39
    {
40
        $fp = fopen($file, 'r');
41
        $this->class = $this->namespace = $buffer = '';
42
        $i = 0;
43
44
        while (!$this->class) {
45
            if (feof($fp)){
46
                break;
47
            }
48
49
            $buffer .= fread($fp, 512);
50
            $tokens = token_get_all($buffer);
51
52
            if (strpos($buffer, '{') === false) {
53
                continue;
54
            }
55
56
            $totalTokens = count($tokens);
57
58
            for (; $i < $totalTokens; $i++) {
59
                if ($tokens[$i][0] === T_NAMESPACE) {
60
                    for ($j = $i + 1; $j < $totalTokens; $j++) {
61
                        if ($tokens[$j][0] === T_STRING) {
62
                            $this->namespace .= '\\'.$tokens[$j][1];
63
                        } else if ($tokens[$j] === '{' || $tokens[$j] === ';') {
64
                            break;
65
                        }
66
                    }
67
                }
68
69
                if ($tokens[$i][0] === T_CLASS) {
70
                    for ($j = $i + 1; $j < $totalTokens; $j++) {
71
                        if ($tokens[$j] === '{') {
72
                            $this->class = $tokens[$i + 2][1];
73
                        }
74
                    }
75
                }
76
77
            }
78
        }
79
    }
80
}