1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Knp\RadBundle\Finder; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\Finder\Finder; |
6
|
|
|
use Symfony\Component\Filesystem\Filesystem; |
7
|
|
|
use Knp\RadBundle\Reflection\ReflectionFactory; |
8
|
|
|
|
9
|
|
|
class ClassFinder |
10
|
|
|
{ |
11
|
|
|
private $finder; |
12
|
|
|
private $filesystem; |
13
|
|
|
private $reflectionFactory; |
14
|
|
|
|
15
|
|
|
public function __construct(Finder $finder = null, Filesystem $filesystem = null, ReflectionFactory $reflectionFactory = null) |
16
|
|
|
{ |
17
|
|
|
$this->finder = $finder ?: new Finder(); |
18
|
|
|
$this->filesystem = $filesystem ?: new Filesystem(); |
19
|
|
|
$this->reflectionFactory = $reflectionFactory ?: new ReflectionFactory(); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function findClasses($directory, $namespace) |
23
|
|
|
{ |
24
|
|
|
if (false === $this->filesystem->exists($directory)) { |
25
|
|
|
return array(); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$classes = array(); |
29
|
|
|
|
30
|
|
|
$this->finder->files(); |
31
|
|
|
$this->finder->name('*.php'); |
32
|
|
|
$this->finder->in($directory); |
33
|
|
|
|
34
|
|
|
foreach ($this->finder->getIterator() as $name) { |
35
|
|
|
$baseName = substr($name, strlen($directory)+1, -4); |
36
|
|
|
$baseClassName = str_replace('/', '\\', $baseName); |
37
|
|
|
|
38
|
|
|
$classes[] = $namespace.'\\'.$baseClassName; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
return $classes; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
public function findClassesMatching($directory, $namespace, $pattern) |
45
|
|
|
{ |
46
|
|
|
$pattern = sprintf('#%s#', str_replace('#', '\#', $pattern)); |
47
|
|
|
$matches = function ($path) use ($pattern) { return preg_match($pattern, $path); }; |
|
|
|
|
48
|
|
|
|
49
|
|
|
return array_values(array_filter($this->findClasses($directory, $namespace), $matches)); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
public function filterClassesImplementing(array $classes, $interface) |
53
|
|
|
{ |
54
|
|
|
$reflectionFactory = $this->reflectionFactory; |
55
|
|
|
|
56
|
|
|
return array_filter($classes, function ($class) use ($interface, $reflectionFactory) { |
57
|
|
|
return $reflectionFactory->createReflectionClass($class)->isSubclassOf($interface); |
58
|
|
|
}); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|