Completed
Push — master ( 3b5440...721fdb )
by Thomas
02:49
created

FindByNamespace::filterData()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 1
nop 1
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
    public function __construct($path = null)
28
    {
29
        $this->path = ($path === null) ? __DIR__ : $path;
30
        $this->data = [];
31
    }
32
33
    public function find($needle = null, $rebuild = false)
34
    {
35
        $this->buildData($rebuild);
36
        return $this->filterData($needle);
37
38
    }
39
40
    protected function buildData($rebuild)
41
    {
42
        if ($rebuild === true || empty($this->data)) {
43
            $allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path));
44
            $phpFiles = new RegexIterator($allFiles, '/\.php$/');
45
            foreach ($phpFiles as $phpFile) {
46
                $content = file_get_contents($phpFile->getRealPath());
47
                $tokens = token_get_all($content);
48
                $namespace = '';
49
                for ($index = 0; isset($tokens[$index]); $index++) {
50
                    if (!isset($tokens[$index][0])) {
51
                        continue;
52
                    }
53
                    if (T_NAMESPACE === $tokens[$index][0]) {
54
                        $index += 2; // Skip namespace keyword and whitespace
55
                        while (isset($tokens[$index]) && is_array($tokens[$index])) {
56
                            $namespace .= $tokens[$index++][1];
57
                        }
58
                    }
59
                    if (T_CLASS === $tokens[$index][0]) {
60
                        $index += 2; // Skip class keyword and whitespace
61
                        $this->data[] = $namespace . '\\' . $tokens[$index][1];
62
                    }
63
                }
64
            }
65
        }
66
    }
67
68
    protected function filterData($needle)
69
    {
70
        return array_values(array_filter($this->data, function ($var) use ($needle) {
71
            if (strpos($var, $needle) !== false) {
72
                return true;
73
            }
74
            return false;
75
        }));
76
    }
77
78
}