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

ClassLocator::getClasses()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 27
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7.0178

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 27
ccs 13
cts 14
cp 0.9286
rs 8.8333
cc 7
nc 10
nop 1
crap 7.0178
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