|
1 | 1 | <?php |
2 | 2 | namespace PHPJava\Utilities; |
3 | 3 |
|
| 4 | +use PHPJava\Core\JavaClass; |
| 5 | +use PHPJava\Core\JavaClassReader; |
| 6 | + |
4 | 7 | class ClassResolver |
5 | 8 | { |
6 | 9 | const MAPS = [ |
7 | 10 | 'String' => '_String', |
8 | 11 | 'Object' => '_Object', |
9 | 12 | ]; |
10 | 13 |
|
11 | | - public static function resolve($javaPath): string |
| 14 | + // resource types |
| 15 | + const RESOURCE_TYPE_FILE = 'RESOURCE_TYPE_FILE'; |
| 16 | + |
| 17 | + // resolved types |
| 18 | + const RESOLVED_TYPE_CLASS = 'RESOLVED_TYPE_CLASS'; |
| 19 | + const RESOLVED_TYPE_IMITATION = 'RESOLVED_TYPE_IMITATION'; |
| 20 | + |
| 21 | + private static $resolves = []; |
| 22 | + private static $resolvedPaths = []; |
| 23 | + |
| 24 | + public static function resolve($javaPath): array |
12 | 25 | { |
13 | 26 | $namespaces = explode('.', str_replace('/', '.', $javaPath)); |
14 | 27 | $buildClassPath = []; |
15 | 28 | foreach ($namespaces as $namespace) { |
16 | 29 | $buildClassPath[] = static::MAPS[$namespace] ?? $namespace; |
17 | 30 | } |
18 | | - return '\\PHPJava\\Imitation\\' . implode('\\', $buildClassPath); |
| 31 | + |
| 32 | + // resolve something approaching |
| 33 | + $relativePath = implode('/', $namespaces); |
| 34 | + foreach (static::$resolves as [$resourceType, $value]) { |
| 35 | + switch ($resourceType) { |
| 36 | + case static::RESOURCE_TYPE_FILE: |
| 37 | + $path = realpath($value . '/' . $relativePath . '.class'); |
| 38 | + if (($key = array_search($path, static::$resolvedPaths, true)) !== false) { |
| 39 | + return static::$resolvedPaths[$key]; |
| 40 | + } |
| 41 | + if (is_file($path)) { |
| 42 | + return $resolvedPaths[] = [ |
| 43 | + static::RESOLVED_TYPE_CLASS, |
| 44 | + new JavaClass(new JavaClassReader($path)), |
| 45 | + ]; |
| 46 | + } |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return [ |
| 52 | + static::RESOLVED_TYPE_IMITATION, |
| 53 | + '\\PHPJava\\Imitation\\' . implode('\\', $buildClassPath), |
| 54 | + ]; |
| 55 | + } |
| 56 | + |
| 57 | + public static function add($valuesOrResourceType = self::RESOURCE_TYPE_FILE, $value = null): void |
| 58 | + { |
| 59 | + if (is_array($valuesOrResourceType)) { |
| 60 | + foreach ($valuesOrResourceType as [$resourceType, $value]) { |
| 61 | + static::add($resourceType, $value); |
| 62 | + } |
| 63 | + |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + if (in_array([$valuesOrResourceType, $value], static::$resolves, true)) { |
| 68 | + return; |
| 69 | + } |
| 70 | + static::$resolves[] = [$valuesOrResourceType, $value]; |
19 | 71 | } |
20 | 72 | } |
0 commit comments