Passed
Branchmaster (fdc5d2)
by Thomas
03:17
created

FindByNamespace::buildData()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 12
ccs 10
cts 10
cp 1
rs 9.2
cc 4
eloc 7
nc 3
nop 1
crap 4
1
<?php
2
3
/**
4
 * Created by PhpStorm.
5
 * User: tom
6
 * Date: 18/06/2016
7
 * Time: 16:23
8
 */
9
10
namespace twhiston\twLib\Discovery;
11
12
use RecursiveDirectoryIterator;
13
use RecursiveIteratorIterator;
14
use RegexIterator;
15
16
class FindByNamespace
17
{
18
19
    protected $path;
20
21
    protected $data;
22
23
    /**
24
     * FindByNamespace constructor.
25
     * @param $path
26
     */
27 1
    public function __construct($path = null)
28
    {
29 1
        $this->path = ($path === null) ? __DIR__ : $path;
30 1
        $this->data = [];
31 1
    }
32
33 1
    public function find($needle = null, $rebuild = false)
34
    {
35 1
        $this->buildData($rebuild);
36 1
        return $this->filterData($needle);
37
38
    }
39
40 1
    protected function buildData($rebuild)
41
    {
42 1
        if ($rebuild === true || empty($this->data)) {
43 1
            $allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path));
44 1
            $phpFiles = new RegexIterator($allFiles, '/\.php$/');
45 1
            foreach ($phpFiles as $phpFile) {
46
                //tokenize file
47 1
                $content = file_get_contents($phpFile->getRealPath());
48 1
                $this->processTokens(token_get_all($content));
49 1
            }
50 1
        }
51 1
    }
52
53 1
    protected function processTokens(array $tokens)
54
    {
55 1
        $namespace = '';
56 1
        for ($index = 0; isset($tokens[$index]); $index++) {
57 1
            if (!isset($tokens[$index][0])) {
58
                continue;
59
            }
60 1
            if (T_NAMESPACE === $tokens[$index][0]) {
61 1
                $index += 2; // Skip namespace keyword and whitespace
62 1
                while (isset($tokens[$index]) && is_array($tokens[$index])) {
63 1
                    $namespace .= $tokens[$index++][1];
64 1
                }
65 1
            }
66 1
            if (T_CLASS === $tokens[$index][0]) {
67 1
                $index += 2; // Skip class keyword and whitespace
68 1
                if (is_array($tokens[$index]) && array_key_exists(1, $tokens[$index])) {
69 1
                    $this->data[] = $namespace . '\\' . $tokens[$index][1];
70 1
                }
71 1
            }
72 1
        }
73 1
    }
74
75
76
    protected function filterData($needle)
77
    {
78 1
        return array_values(array_filter($this->data, function ($var) use ($needle) {
79 1
            if (strpos($var, $needle) !== false) {
80 1
                return true;
81
            }
82 1
            return false;
83 1
        }));
84
    }
85
86
}