ClassFinder::findClasses()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 21
rs 9.3142
c 0
b 0
f 0
cc 3
eloc 12
nc 3
nop 2
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); };
0 ignored issues
show
Coding Style introduced by
Opening brace must be the last content on the line
Loading history...
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
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