forked from api-platform/core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReflectionClassRecursiveIterator.php
91 lines (78 loc) · 2.58 KB
/
ReflectionClassRecursiveIterator.php
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
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Metadata\Util;
/**
* Gets reflection classes for php files in the given directories.
*
* @author Antoine Bluchet <[email protected]>
*
* @internal
*/
final class ReflectionClassRecursiveIterator
{
/**
* @var array<string, array<class-string, \ReflectionClass>>
*/
private static array $localCache;
private function __construct()
{
}
/**
* @param string[] $directories
*
* @return array<class-string, \ReflectionClass>
*/
public static function getReflectionClassesFromDirectories(array $directories): array
{
$id = hash('xxh3', implode('', $directories));
if (isset(self::$localCache[$id])) {
return self::$localCache[$id];
}
$includedFiles = [];
foreach ($directories as $path) {
$iterator = new \RegexIterator(
new \RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS | \FilesystemIterator::FOLLOW_SYMLINKS),
\RecursiveIteratorIterator::LEAVES_ONLY
),
'/^(?!.*Test\.php$).+\.php$/i',
\RecursiveRegexIterator::GET_MATCH
);
foreach ($iterator as $file) {
$sourceFile = $file[0];
if (!preg_match('(^phar:)i', (string) $sourceFile)) {
$sourceFile = realpath($sourceFile);
}
try {
require_once $sourceFile;
} catch (\Throwable) {
// invalid PHP file (example: missing parent class)
continue;
}
$includedFiles[$sourceFile] = true;
}
}
$sortedClasses = get_declared_classes();
sort($sortedClasses);
$sortedInterfaces = get_declared_interfaces();
sort($sortedInterfaces);
$declared = [...$sortedClasses, ...$sortedInterfaces];
$ret = [];
foreach ($declared as $className) {
$reflectionClass = new \ReflectionClass($className);
$sourceFile = $reflectionClass->getFileName();
if (isset($includedFiles[$sourceFile])) {
$ret[$className] = $reflectionClass;
}
}
return self::$localCache[$id] = $ret;
}
}