Completed
Push — master ( 47cd69...3b5440 )
by Thomas
02:46
created

FindByNamespace   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 13
c 1
b 0
f 1
lcom 1
cbo 0
dl 0
loc 57
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 2
C find() 0 37 11
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 RecursiveIteratorIterator;
13
use RecursiveDirectoryIterator;
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
        if($rebuild === TRUE || empty($this->data))
36
        {
37
            $allFiles = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->path));
38
            $phpFiles = new RegexIterator($allFiles, '/\.php$/');
39
            foreach ($phpFiles as $phpFile) {
40
                $content = file_get_contents($phpFile->getRealPath());
41
                $tokens = token_get_all($content);
42
                $namespace = '';
43
                for ($index = 0; isset($tokens[$index]); $index++) {
44
                    if (!isset($tokens[$index][0])) {
45
                        continue;
46
47
                    }
48
                    if (T_NAMESPACE === $tokens[$index][0]) {
49
                        $index += 2; // Skip namespace keyword and whitespace
50
                        while (isset($tokens[$index]) && is_array($tokens[$index])) {
51
                            $namespace .= $tokens[$index++][1];
52
                        }
53
                    }
54
                    if (T_CLASS === $tokens[$index][0]) {
55
                        $index += 2; // Skip class keyword and whitespace
56
                        $this->data[] = $namespace.'\\'.$tokens[$index][1];
57
                    }
58
                }
59
            }
60
        }
61
62
        return array_values(array_filter($this->data, function ($var) use ($needle) {
63
            if (strpos($var, $needle) !== false) {
64
                return TRUE;
65
            }
66
            return FALSE;
67
        }));
68
69
    }
70
71
72
}