Passed
Push — master ( 904fca...2ba06e )
by butschster
07:38
created

ClassLocator   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 96%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 13
eloc 25
c 1
b 0
f 0
dl 0
loc 67
ccs 24
cts 25
cp 0.96
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
B getClasses() 0 27 7
A availableClasses() 0 9 2
A isTargeted() 0 13 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Tokenizer;
6
7
use Spiral\Tokenizer\Exception\LocatorException;
8
9
/**
10
 * Can locate classes in a specified directory.
11
 */
12
final class ClassLocator extends AbstractLocator implements ClassesInterface
13
{
14
    public const INJECTOR = ClassLocatorInjector::class;
15
16 312
    public function getClasses(object|string|null $target = null): array
17
    {
18 312
        if (!empty($target)) {
19 29
            $target = new \ReflectionClass($target);
20
        }
21
22 312
        $result = [];
23 312
        foreach ($this->availableClasses() as $class) {
24
            try {
25 312
                $reflection = $this->classReflection($class);
26 276
            } catch (LocatorException $e) {
27 276
                if ($this->debug) {
28
                    throw $e;
29
                }
30
31
                //Ignoring
32 276
                continue;
33
            }
34
35 312
            if (!$this->isTargeted($reflection, $target) || $reflection->isInterface()) {
36 29
                continue;
37
            }
38
39 312
            $result[$reflection->getName()] = $reflection;
40
        }
41
42 312
        return $result;
43
    }
44
45
    /**
46
     * Classes available in finder scope.
47
     *
48
     * @return class-string[]
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string[] at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string[].
Loading history...
49
     */
50 312
    protected function availableClasses(): array
51
    {
52 312
        $classes = [];
53
54 312
        foreach ($this->availableReflections() as $reflection) {
55 312
            $classes = \array_merge($classes, $reflection->getClasses());
56
        }
57
58 312
        return $classes;
59
    }
60
61
    /**
62
     * Check if given class targeted by locator.
63
     *
64
     * @param \ReflectionClass|null $target
65
     */
66 312
    protected function isTargeted(\ReflectionClass $class, \ReflectionClass $target = null): bool
67
    {
68 312
        if (empty($target)) {
69 303
            return true;
70
        }
71
72 29
        if (!$target->isTrait()) {
73
            //Target is interface or class
74 5
            return $class->isSubclassOf($target) || $class->getName() === $target->getName();
75
        }
76
77
        // Checking using traits
78 24
        return \in_array($target->getName(), $this->fetchTraits($class->getName()));
79
    }
80
}
81