-
Notifications
You must be signed in to change notification settings - Fork 3
/
ClassNameMapper.php
322 lines (288 loc) · 11.6 KB
/
ClassNameMapper.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<?php
namespace Mouf\Composer;
/**
* The class maps a class name to one or many possible file names according to PSR-0 or PSR-4 rules.
*
* @author David Négrier <david@mouf-php.com>
*/
class ClassNameMapper
{
/**
*
* @var array<namespace, path[]>
*/
private $psr0Namespaces = array();
/**
*
* @var array<namespace, path[]>
*/
private $psr4Namespaces = array();
/**
* Registers a PSR-0 namespace.
*
* @param string $namespace The namespace to register
* @param string|array $path The path on the filesystem (or an array of paths)
*/
public function registerPsr0Namespace($namespace, $path) {
// A namespace always ends with a \
$namespace = trim($namespace, '\\').'\\';
if ($namespace === '\\') {
$namespace = '';
}
if (!is_array($path)) {
$path = [$path];
}
// Paths always end with a /
$paths = array_map(function($path) {
return rtrim($path, '\\/').'/';
}, $path);
if (!isset($this->psr0Namespaces[$namespace])) {
$this->psr0Namespaces[$namespace] = $paths;
} else {
$this->psr0Namespaces[$namespace] = array_merge($this->psr0Namespaces[$namespace], $paths);
}
}
/**
* Registers a PSR-4 namespace.
*
* @param string $namespace The namespace to register
* @param string|array $path The path on the filesystem (or an array of paths)
*/
public function registerPsr4Namespace($namespace, $path) {
// A namespace always ends with a \
$namespace = trim($namespace, '\\').'\\';
if ($namespace === '\\') {
$namespace = '';
}
if (!is_array($path)) {
$path = [$path];
}
// Paths always end with a /
$paths = array_map(function($path) {
return rtrim($path, '\\/').'/';
}, $path);
if (!isset($this->psr4Namespaces[$namespace])) {
$this->psr4Namespaces[$namespace] = $paths;
} else {
$this->psr4Namespaces[$namespace] = array_merge($this->psr4Namespaces[$namespace], $paths);
}
}
/**
* @param string $composerJsonPath
* @param string $rootPath
* @param bool $useAutoloadDev
* @return ClassNameMapper
*/
public static function createFromComposerFile($composerJsonPath = null, $rootPath = null, $useAutoloadDev = false) {
$classNameMapper = new ClassNameMapper();
if ($composerJsonPath === null) {
$composerJsonPath = __DIR__.'/../../../../composer.json';
}
$classNameMapper->loadComposerFile($composerJsonPath, $rootPath, $useAutoloadDev);
return $classNameMapper;
}
/**
*
* @param string $composerJsonPath Path to the composer file
* @param string $rootPath Root path of the project (or null)
*/
public function loadComposerFile($composerJsonPath, $rootPath = null, $useAutoloadDev = false) {
$composer = json_decode(file_get_contents($composerJsonPath), true);
if ($rootPath) {
$relativePath = self::makePathRelative(dirname($composerJsonPath), $rootPath);
} else {
$relativePath = null;
}
if (isset($composer["autoload"]["psr-0"])) {
$psr0 = $composer["autoload"]["psr-0"];
foreach ($psr0 as $namespace => $paths) {
if ($relativePath != null) {
if (!is_array($paths)) {
$paths = [$paths];
}
$paths = array_map(function($path) use ($relativePath) {
return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
}, $paths);
}
$this->registerPsr0Namespace($namespace, $paths);
}
}
if (isset($composer["autoload"]["psr-4"])) {
$psr4 = $composer["autoload"]["psr-4"];
foreach ($psr4 as $namespace => $paths) {
if ($relativePath != null) {
if (!is_array($paths)) {
$paths = [$paths];
}
$paths = array_map(function($path) use ($relativePath) {
return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
}, $paths);
}
$this->registerPsr4Namespace($namespace, $paths);
}
}
if ($useAutoloadDev) {
if (isset($composer["autoload-dev"]["psr-0"])) {
$psr0 = $composer["autoload-dev"]["psr-0"];
foreach ($psr0 as $namespace => $paths) {
if ($relativePath != null) {
if (!is_array($paths)) {
$paths = [$paths];
}
$paths = array_map(function($path) use ($relativePath) {
return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
}, $paths);
}
$this->registerPsr0Namespace($namespace, $paths);
}
}
if (isset($composer["autoload-dev"]["psr-4"])) {
$psr4 = $composer["autoload-dev"]["psr-4"];
foreach ($psr4 as $namespace => $paths) {
if ($relativePath != null) {
if (!is_array($paths)) {
$paths = [$paths];
}
$paths = array_map(function($path) use ($relativePath) {
return rtrim($relativePath,'\\/').'/'.ltrim($path, '\\/');
}, $paths);
}
$this->registerPsr4Namespace($namespace, $paths);
}
}
}
return $this;
}
/**
* Given an existing path, convert it to a path relative to a given starting path.
* Shamelessly borrowed to Symfony :). Thanks guys.
* Note: we do not include Symfony's "FileSystem" component to avoid adding too many dependencies.
*
* @param string $endPath Absolute path of target
* @param string $startPath Absolute path where traversal begins
*
* @return string Path of target relative to starting path
*/
private static function makePathRelative($endPath, $startPath)
{
// Normalize separators on Windows
if ('\\' === DIRECTORY_SEPARATOR) {
$endPath = strtr($endPath, '\\', '/');
$startPath = strtr($startPath, '\\', '/');
}
// Split the paths into arrays
$startPathArr = explode('/', trim($startPath, '/'));
$endPathArr = explode('/', trim($endPath, '/'));
// Find for which directory the common path stops
$index = 0;
while (isset($startPathArr[$index]) && isset($endPathArr[$index]) && $startPathArr[$index] === $endPathArr[$index]) {
$index++;
}
// Determine how deep the start path is relative to the common path (ie, "web/bundles" = 2 levels)
$depth = count($startPathArr) - $index;
// Repeated "../" for each level need to reach the common path
$traverser = str_repeat('../', $depth);
$endPathRemainder = implode('/', array_slice($endPathArr, $index));
// Construct $endPath from traversing to the common path, then to the remaining $endPath
$relativePath = $traverser.(strlen($endPathRemainder) > 0 ? $endPathRemainder.'/' : '');
return (strlen($relativePath) === 0) ? './' : $relativePath;
}
/**
* Returns a list of all namespaces that are managed by the ClassNameMapper.
*
* @return string[]
*/
public function getManagedNamespaces() {
return array_keys(array_merge($this->psr0Namespaces, $this->psr4Namespaces));
}
/**
* Returns a list of paths that can be used to store $className.
*
* @param string $className
* @return string[]
*/
public function getPossibleFileNames($className) {
$possibleFileNames = array();
$className = ltrim($className, '\\');
$psr0unfactorizedAutoload = $this->unfactorizeAutoload($this->psr0Namespaces);
foreach ($psr0unfactorizedAutoload as $result) {
$namespace = $result['namespace'];
$directory = $result['directory'];
if ($namespace === '') {
$tmpClassName = $className;
if ($lastNsPos = strripos($tmpClassName, '\\')) {
$namespace = substr($tmpClassName, 0, $lastNsPos);
$tmpClassName = substr($tmpClassName, $lastNsPos + 1);
}
$fileName = str_replace('\\', '/', $namespace) . '/' . str_replace('_', '/', $tmpClassName) . '.php';
$possibleFileNames[] = $directory.$fileName;
} else {
if (strpos($className, $namespace) === 0) {
$tmpClassName = $className;
$fileName = '';
if ($lastNsPos = strripos($tmpClassName, '\\')) {
$namespace = substr($tmpClassName, 0, $lastNsPos);
$tmpClassName = substr($tmpClassName, $lastNsPos + 1);
$fileName = str_replace('\\', '/', $namespace) . '/';
}
$fileName .= str_replace('_', '/', $tmpClassName) . '.php';
$possibleFileNames[] = $directory.$fileName;
}
}
}
$psr4unfactorizedAutoload = $this->unfactorizeAutoload($this->psr4Namespaces);
foreach ($psr4unfactorizedAutoload as $result) {
$namespace = $result['namespace'];
$directory = $result['directory'];
if ($namespace === '') {
$fileName = str_replace('\\', '/', $className) . '.php';
$possibleFileNames[] = $directory.$fileName;
} else {
if (strpos($className, $namespace) === 0) {
$shortenedClassName = substr($className, strlen($namespace));
if ($lastNsPos = strripos($shortenedClassName, '\\')) {
$namespace = substr($shortenedClassName, 0, $lastNsPos);
$shortenedClassName = substr($shortenedClassName, $lastNsPos + 1);
$fileName = str_replace('\\', '/', $namespace) . '/' . $shortenedClassName;
} else {
$fileName = $shortenedClassName;
}
$fileName .= '.php';
$possibleFileNames[] = $directory . $fileName;
}
}
}
return $possibleFileNames;
}
/**
* Takes in parameter an array like
* [{ "Mouf": "src/" }] or [{ "Mouf": ["src/", "src2/"] }] .
* returns
* [
* {"namespace"=> "Mouf", "directory"=>"src/"},
* {"namespace"=> "Mouf", "directory"=>"src2/"}
* ]
*
* @param array $autoload
* @return array<int, array<string, string>>
*/
private static function unfactorizeAutoload(array $autoload) {
$result = array();
foreach ($autoload as $namespace => $directories) {
if (!is_array($directories)) {
$result[] = array(
"namespace" => $namespace,
"directory" => trim($directories, '/\\').'/'
);
} else {
foreach ($directories as $dir) {
$result[] = array(
"namespace" => $namespace,
"directory" => trim($dir, '/').'/'
);
}
}
}
return $result;
}
}