ClassFinder   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 3

Importance

Changes 0
Metric Value
wmc 9
lcom 2
cbo 3
dl 0
loc 52
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 4
A findClasses() 0 21 3
A findClassesMatching() 0 7 1
A filterClassesImplementing() 0 8 1
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