1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Antidot\DevTools\Application\Service; |
6
|
|
|
|
7
|
|
|
use Composer\Autoload\ClassLoader; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
|
10
|
|
|
use function array_key_exists; |
11
|
|
|
use function is_array; |
12
|
|
|
use function is_string; |
13
|
|
|
use function spl_autoload_functions; |
14
|
|
|
use function sprintf; |
15
|
|
|
|
16
|
|
|
class GetRealPathFromNamespace |
17
|
|
|
{ |
18
|
|
|
/** @var GetClassNameFromFQCN */ |
19
|
|
|
private $getClassNameFromFQCN; |
20
|
|
|
/** @var GetNamespaceFromFQCN */ |
21
|
|
|
private $getNamespaceFromFQCN; |
22
|
|
|
|
23
|
|
|
public function __construct( |
24
|
|
|
GetClassNameFromFQCN $getClassNameFromFQCN, |
25
|
|
|
GetNamespaceFromFQCN $getNamespaceFromFQCN |
26
|
|
|
) { |
27
|
|
|
$this->getClassNameFromFQCN = $getClassNameFromFQCN; |
28
|
|
|
$this->getNamespaceFromFQCN = $getNamespaceFromFQCN; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
public function __invoke(string $namespace): string |
32
|
|
|
{ |
33
|
|
|
$classDir = null; |
34
|
|
|
$parts = ''; |
35
|
|
|
$getClassNameFromFQCN = $this->getClassNameFromFQCN; |
36
|
|
|
$getNamespaceFromFQCN = $this->getNamespaceFromFQCN; |
37
|
|
|
$initialNamespace = $namespace; |
38
|
|
|
$autoloadFunctions = spl_autoload_functions(); |
39
|
|
|
if (!is_array($autoloadFunctions)) { |
|
|
|
|
40
|
|
|
throw new \RuntimeException('Your autoload stack is not activated'); |
41
|
|
|
} |
42
|
|
|
foreach ($autoloadFunctions as $autoloader) { |
43
|
|
|
/** @var ClassLoader $classLoader */ |
44
|
|
|
$classLoader = $autoloader[0]; |
45
|
|
|
$depth = 0; |
46
|
|
|
while (null === $classDir) { |
47
|
|
|
if (array_key_exists($namespace . "\\", $classLoader->getPrefixesPsr4())) { |
48
|
|
|
$classDir = $classLoader->getPrefixesPsr4()[$namespace . "\\"][0]; |
49
|
|
|
} else { |
50
|
|
|
$parts = DIRECTORY_SEPARATOR . $getClassNameFromFQCN($namespace) . $parts; |
51
|
|
|
$namespace = $getNamespaceFromFQCN($namespace); |
52
|
|
|
} |
53
|
|
|
if (10 <= $depth) { |
54
|
|
|
throw new InvalidArgumentException(sprintf( |
55
|
|
|
'Invalid Class name given, the namespace %s is not in autoloader configured namespaces', |
56
|
|
|
$initialNamespace |
57
|
|
|
)); |
58
|
|
|
} |
59
|
|
|
$depth++; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
if (false === is_string($classDir)) { |
64
|
|
|
throw new InvalidArgumentException(sprintf( |
65
|
|
|
'Invalid Class name given, the namespace %s is not in autoloader configured namespaces', |
66
|
|
|
$initialNamespace |
67
|
|
|
)); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
return $classDir . $parts; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|