-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassFinder.php
More file actions
99 lines (79 loc) · 2.08 KB
/
ClassFinder.php
File metadata and controls
99 lines (79 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
<?php
namespace App\Service;
use Symfony\Component\Finder\Finder;
class ClassFinder
{
public function __construct( private string $projectDir ) {}
public function getRootNamespace(): string
{
return 'App';
}
public function getRootDir( bool $trail = false ): string
{
return $this->projectDir . ( ( $trail ) ? DIRECTORY_SEPARATOR : '' );
}
/**
* @param string $namespace
*
* @return array
*/
public function getClassesInNamespace( string $namespace ): array
{
$classes = [];
$finder = new Finder();
$dir = trim( str_replace( [ '\\', "\\", "/" ], DIRECTORY_SEPARATOR, $namespace ), "\/\\" );
if ( str_starts_with( $dir, $this->getRootNamespace() ) ) {
$dir = 'src' . substr( $dir, 3 );
}
$path = $this->getRootDir( true ) . $dir;
if ( ! is_dir( $path ) ) {
return [];
}
$finder->files()->in( $path )->name( '*.php' );
foreach ( $finder as $file ) {
$file_name = $file->getFilenameWithoutExtension();
$class_name = rtrim( $namespace, '\\' ) . '\\' . $file_name;
if ( class_exists( $class_name ) ) {
try {
$classes[] = $class_name;
} catch ( \Throwable $e ) {
// @todo Notice?
continue;
}
}
}
return $classes;
}
/**
* @param string $dir
*
* @return array
*/
public function getClassesInDir( string $dir ): array
{
$classes = [];
$finder = new Finder();
$namespace = str_replace( [ '\\', "\\", "/", DIRECTORY_SEPARATOR ], "\\", $dir );
$path = $this->getRootDir( true ) . trim( $dir, "\/\\" );
if ( str_starts_with( $dir, 'src' ) ) {
$namespace = $this->getRootNamespace() . substr( $namespace, 3 );
}
if ( ! is_dir( $path ) ) {
return [];
}
$finder->files()->in( $path )->depth( '1' )->name( '*.php' );
foreach ( $finder as $file ) {
$file_name = $file->getFilenameWithoutExtension();
$class_name = rtrim( $namespace, '\\' ) . "\\" . $file_name . "\\" . $file_name;
if ( class_exists( $class_name ) ) {
try {
$classes[] = $class_name;
} catch ( \Throwable $e ) {
// @todo Notice?
continue;
}
}
}
return $classes;
}
}