forked from composer/class-map-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClassMapGenerator.php
More file actions
351 lines (305 loc) · 13.6 KB
/
ClassMapGenerator.php
File metadata and controls
351 lines (305 loc) · 13.6 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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
<?php declare(strict_types=1);
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/*
* This file was initially based on a version from the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*/
namespace Composer\ClassMapGenerator;
use Composer\Pcre\Preg;
use Symfony\Component\Finder\Finder;
use Composer\IO\IOInterface;
/**
* ClassMapGenerator
*
* @author Gyula Sallai <salla016@gmail.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class ClassMapGenerator
{
/**
* @var list<string>
*/
private $extensions;
/**
* @var FileList|null
*/
private $scannedFiles = null;
/**
* @var ClassMap
*/
private $classMap;
/**
* @var non-empty-string
*/
private $streamWrappersRegex;
/**
* @param list<string> $extensions File extensions to scan for classes in the given paths
*/
public function __construct(array $extensions = ['php', 'inc'])
{
$this->extensions = $extensions;
$this->classMap = new ClassMap;
$this->streamWrappersRegex = sprintf('{^(?:%s)://}', implode('|', array_map('preg_quote', stream_get_wrappers())));
}
/**
* When calling scanPaths repeatedly with paths that may overlap, calling this will ensure that the same class is never scanned twice
*
* You can provide your own FileList instance or use the default one if you pass no argument
*
* @return $this
*/
public function avoidDuplicateScans(?FileList $scannedFiles = null): self
{
$this->scannedFiles = $scannedFiles ?? new FileList;
return $this;
}
/**
* Iterate over all files in the given directory searching for classes
*
* @param string|\Traversable<\SplFileInfo>|array<\SplFileInfo> $path The path to search in or an array/traversable of SplFileInfo (e.g. symfony/finder instance)
* @return array<class-string, non-empty-string> A class map array
*
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public static function createMap($path): array
{
$generator = new self();
$generator->scanPaths($path);
return $generator->getClassMap()->getMap();
}
public function getClassMap(): ClassMap
{
return $this->classMap;
}
/**
* Iterate over all files in the given directory searching for classes
*
* @param string|\Traversable<\SplFileInfo>|array<\SplFileInfo> $path The path to search in or an array/traversable of SplFileInfo (e.g. symfony/finder instance)
* @param non-empty-string|null $excluded Regex that matches file paths to be excluded from the classmap
* @param 'classmap'|'psr-0'|'psr-4' $autoloadType Optional autoload standard to use mapping rules with the namespace instead of purely doing a classmap
* @param string|null $namespace Optional namespace prefix to filter by, only for psr-0/psr-4 autoloading
* @param array<string> $excludedDirs Optional dirs to exclude from search relative to $path
*
* @throws \RuntimeException When the path is neither an existing file nor directory
*/
public function scanPaths($path, ?string $excluded = null, string $autoloadType = 'classmap', ?string $namespace = null, array $excludedDirs = []): void
{
if (!in_array($autoloadType, ['psr-0', 'psr-4', 'classmap'], true)) {
throw new \InvalidArgumentException('$autoloadType must be one of: "psr-0", "psr-4" or "classmap"');
}
if ('classmap' !== $autoloadType) {
if (!is_string($path)) {
throw new \InvalidArgumentException('$path must be a string when specifying a psr-0 or psr-4 autoload type');
}
if (!is_string($namespace)) {
throw new \InvalidArgumentException('$namespace must be given (even if it is an empty string if you do not want to filter) when specifying a psr-0 or psr-4 autoload type');
}
$basePath = $path;
}
if (is_string($path)) {
if (is_file($path)) {
$path = [new \SplFileInfo($path)];
} elseif (is_dir($path) || strpos($path, '*') !== false) {
$path = Finder::create()
->files()
->followLinks()
->name('/\.(?:'.implode('|', array_map('preg_quote', $this->extensions)).')$/')
->in($path)
->exclude($excludedDirs);
} else {
throw new \RuntimeException(
'Could not scan for classes inside "'.$path.'" which does not appear to be a file nor a folder'
);
}
}
$cwd = realpath(self::getCwd());
foreach ($path as $file) {
$filePath = $file->getPathname();
if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), $this->extensions, true)) {
continue;
}
$isStreamWrapperPath = Preg::isMatch($this->streamWrappersRegex, $filePath);
if (!self::isAbsolutePath($filePath) && !$isStreamWrapperPath) {
$filePath = $cwd . '/' . $filePath;
$filePath = self::normalizePath($filePath);
} else {
$filePath = Preg::replace('{(?<!:)[\\\\/]{2,}}', '/', $filePath);
}
if ('' === $filePath) {
throw new \LogicException('Got an empty $filePath for '.$file->getPathname());
}
$realPath = $isStreamWrapperPath
? $filePath
: realpath($filePath);
// fallback just in case but this really should not happen
if (false === $realPath) {
throw new \RuntimeException('realpath of '.$filePath.' failed to resolve, got false');
}
// if a list of scanned files is given, avoid scanning twice the same file to save cycles and avoid generating warnings
// in case a PSR-0/4 declaration follows another more specific one, or a classmap declaration, which covered this file already
if ($this->scannedFiles !== null && $this->scannedFiles->contains($realPath)) {
continue;
}
// check the realpath of the file against the excluded paths as the path might be a symlink and the excluded path is realpath'd so symlink are resolved
if (null !== $excluded && Preg::isMatch($excluded, strtr($realPath, '\\', '/'))) {
continue;
}
// check non-realpath of file for directories symlink in project dir
if (null !== $excluded && Preg::isMatch($excluded, strtr($filePath, '\\', '/'))) {
continue;
}
$classes = PhpFileParser::findClasses($filePath);
if ('classmap' !== $autoloadType && isset($namespace)) {
$classes = $this->filterByNamespace($classes, $filePath, $namespace, $autoloadType, $basePath);
// if no valid class was found in the file then we do not mark it as scanned as it might still be matched by another rule later
if (\count($classes) > 0 && $this->scannedFiles !== null) {
$this->scannedFiles->add($realPath);
}
} elseif ($this->scannedFiles !== null) {
// classmap autoload rules always collect all classes so for these we definitely do not want to scan again
$this->scannedFiles->add($realPath);
}
foreach ($classes as $class) {
if (!$this->classMap->hasClass($class)) {
$this->classMap->addClass($class, $filePath);
} elseif ($filePath !== $this->classMap->getClassPath($class)) {
$this->classMap->addAmbiguousClass($class, $filePath);
}
}
}
}
/**
* Remove classes which could not have been loaded by namespace autoloaders
*
* @param array<int, class-string> $classes found classes in given file
* @param string $filePath current file
* @param string $baseNamespace prefix of given autoload mapping
* @param 'psr-0'|'psr-4' $namespaceType
* @param string $basePath root directory of given autoload mapping
* @return array<int, class-string> valid classes
*
* @throws \InvalidArgumentException When namespaceType is neither psr-0 nor psr-4
*/
private function filterByNamespace(array $classes, string $filePath, string $baseNamespace, string $namespaceType, string $basePath): array
{
$validClasses = [];
$rejectedClasses = [];
$realSubPath = substr($filePath, strlen($basePath) + 1);
$dotPosition = strrpos($realSubPath, '.');
$realSubPath = substr($realSubPath, 0, $dotPosition === false ? PHP_INT_MAX : $dotPosition);
foreach ($classes as $class) {
// transform class name to file path and validate
if ('psr-0' === $namespaceType) {
$namespaceLength = strrpos($class, '\\');
if (false !== $namespaceLength) {
$namespace = substr($class, 0, $namespaceLength + 1);
$className = substr($class, $namespaceLength + 1);
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $namespace)
. str_replace('_', DIRECTORY_SEPARATOR, $className);
} else {
$subPath = str_replace('_', DIRECTORY_SEPARATOR, $class);
}
} elseif ('psr-4' === $namespaceType) {
$subNamespace = ('' !== $baseNamespace) ? substr($class, strlen($baseNamespace)) : $class;
$subPath = str_replace('\\', DIRECTORY_SEPARATOR, $subNamespace);
} else {
throw new \InvalidArgumentException('$namespaceType must be "psr-0" or "psr-4"');
}
if ($subPath === $realSubPath) {
$validClasses[] = $class;
} else {
$rejectedClasses[] = $class;
}
}
// warn only if no valid classes, else silently skip invalid
if (\count($validClasses) === 0) {
$cwd = realpath(self::getCwd());
if ($cwd === false) {
$cwd = self::getCwd();
}
$cwd = self::normalizePath($cwd);
$shortPath = Preg::replace('{^'.preg_quote($cwd).'}', '.', self::normalizePath($filePath), 1);
$shortBasePath = Preg::replace('{^'.preg_quote($cwd).'}', '.', self::normalizePath($basePath), 1);
foreach ($rejectedClasses as $class) {
$this->classMap->addPsrViolation("Class $class located in $shortPath does not comply with $namespaceType autoloading standard (rule: $baseNamespace => $shortBasePath). Skipping.", $class, $filePath);
}
return [];
}
return $validClasses;
}
/**
* Checks if the given path is absolute
*
* @see Composer\Util\Filesystem::isAbsolutePath
*
* @param string $path
* @return bool
*/
private static function isAbsolutePath(string $path): bool
{
return strpos($path, '/') === 0 || substr($path, 1, 1) === ':' || strpos($path, '\\\\') === 0;
}
/**
* Normalize a path. This replaces backslashes with slashes, removes ending
* slash and collapses redundant separators and up-level references.
*
* @see Composer\Util\Filesystem::normalizePath
*
* @param string $path Path to the file or directory
* @return string
*/
private static function normalizePath(string $path): string
{
$parts = [];
$path = strtr($path, '\\', '/');
$prefix = '';
$absolute = '';
// extract windows UNC paths e.g. \\foo\bar
if (strpos($path, '//') === 0 && \strlen($path) > 2) {
$absolute = '//';
$path = substr($path, 2);
}
// extract a prefix being a protocol://, protocol:, protocol://drive: or simply drive:
if (Preg::isMatchStrictGroups('{^( [0-9a-z]{2,}+: (?: // (?: [a-z]: )? )? | [a-z]: )}ix', $path, $match)) {
$prefix = $match[1];
$path = substr($path, \strlen($prefix));
}
if (strpos($path, '/') === 0) {
$absolute = '/';
$path = substr($path, 1);
}
$up = false;
foreach (explode('/', $path) as $chunk) {
if ('..' === $chunk && (\strlen($absolute) > 0 || $up)) {
array_pop($parts);
$up = !(\count($parts) === 0 || '..' === end($parts));
} elseif ('.' !== $chunk && '' !== $chunk) {
$parts[] = $chunk;
$up = '..' !== $chunk;
}
}
// ensure c: is normalized to C:
$prefix = Preg::replaceCallback('{(?:^|://)[a-z]:$}i', function (array $m) { return strtoupper((string) $m[0]); }, $prefix);
return $prefix.$absolute.implode('/', $parts);
}
/**
* @see Composer\Util\Platform::getCwd
*/
private static function getCwd(): string
{
$cwd = getcwd();
if (false === $cwd) {
throw new \RuntimeException('Could not determine the current working directory');
}
return $cwd;
}
}