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 |
|
$this->data[$path] = []; |
32
|
1 |
|
} |
33
|
|
|
|
34
|
|
|
public function setPath($path) |
35
|
|
|
{ |
36
|
|
|
$this->path = $path; |
37
|
|
|
} |
38
|
|
|
|
39
|
1 |
|
public function find($needle = null, $rebuild = false) |
40
|
|
|
{ |
41
|
1 |
|
$this->buildData($rebuild); |
42
|
1 |
|
return $this->filterData($needle); |
43
|
|
|
|
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
protected function buildData($rebuild) |
47
|
|
|
{ |
48
|
1 |
|
if ($rebuild === true || empty($this->data[$this->path])) { |
49
|
1 |
|
$allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path)); |
50
|
1 |
|
$phpFiles = new RegexIterator($allFiles, '/\.php$/'); |
51
|
1 |
|
foreach ($phpFiles as $phpFile) { |
52
|
|
|
//tokenize file |
53
|
1 |
|
$content = file_get_contents($phpFile->getRealPath()); |
54
|
1 |
|
$this->processTokens(token_get_all($content)); |
55
|
1 |
|
} |
56
|
1 |
|
} |
57
|
1 |
|
} |
58
|
|
|
|
59
|
1 |
|
protected function processTokens(array $tokens) |
60
|
|
|
{ |
61
|
1 |
|
$namespace = ''; |
62
|
1 |
|
for ($index = 0; isset($tokens[$index]); $index++) { |
63
|
1 |
|
if (!isset($tokens[$index][0])) { |
64
|
|
|
continue; |
65
|
|
|
} |
66
|
1 |
|
if (T_NAMESPACE === $tokens[$index][0]) { |
67
|
1 |
|
$index += 2; // Skip namespace keyword and whitespace |
68
|
1 |
|
while (isset($tokens[$index]) && is_array($tokens[$index])) { |
69
|
1 |
|
$namespace .= $tokens[$index++][1]; |
70
|
1 |
|
} |
71
|
1 |
|
} |
72
|
1 |
|
if (T_CLASS === $tokens[$index][0]) { |
73
|
1 |
|
$index += 2; // Skip class keyword and whitespace |
74
|
1 |
|
if (is_array($tokens[$index]) && array_key_exists(1, $tokens[$index])) { |
75
|
1 |
|
$this->data[$this->path][] = $namespace . '\\' . $tokens[$index][1]; |
76
|
1 |
|
} |
77
|
1 |
|
} |
78
|
1 |
|
} |
79
|
1 |
|
} |
80
|
|
|
|
81
|
|
|
|
82
|
|
|
protected function filterData($needle) |
83
|
|
|
{ |
84
|
1 |
|
return array_values(array_filter($this->data[$this->path], function ($var) use ($needle) { |
85
|
1 |
|
if (strpos($var, $needle) !== false) { |
86
|
1 |
|
return true; |
87
|
|
|
} |
88
|
1 |
|
return false; |
89
|
1 |
|
})); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
} |