forked from codeigniter4/CodeIgniter4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAutoloader.php
485 lines (414 loc) · 14 KB
/
Autoloader.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Autoloader;
use CodeIgniter\Exceptions\ConfigException;
use Composer\Autoload\ClassLoader;
use Composer\InstalledVersions;
use Config\Autoload;
use Config\Modules;
use InvalidArgumentException;
use RuntimeException;
/**
* An autoloader that uses both PSR4 autoloading, and traditional classmaps.
*
* Given a foo-bar package of classes in the file system at the following paths:
* ```
* /path/to/packages/foo-bar/
* /src
* Baz.php # Foo\Bar\Baz
* Qux/
* Quux.php # Foo\Bar\Qux\Quux
* ```
* you can add the path to the configuration array that is passed in the constructor.
* The Config array consists of 2 primary keys, both of which are associative arrays:
* 'psr4', and 'classmap'.
* ```
* $Config = [
* 'psr4' => [
* 'Foo\Bar' => '/path/to/packages/foo-bar'
* ],
* 'classmap' => [
* 'MyClass' => '/path/to/class/file.php'
* ]
* ];
* ```
* Example:
* ```
* <?php
* // our configuration array
* $Config = [ ... ];
* $loader = new \CodeIgniter\Autoloader\Autoloader($Config);
*
* // register the autoloader
* $loader->register();
* ```
*/
class Autoloader
{
/**
* Stores namespaces as key, and path as values.
*
* @var array<string, array<string>>
*/
protected $prefixes = [];
/**
* Stores class name as key, and path as values.
*
* @var array<string, string>
*/
protected $classmap = [];
/**
* Stores files as a list.
*
* @var string[]
* @phpstan-var list<string>
*/
protected $files = [];
/**
* Stores helper list.
* Always load the URL helper, it should be used in most apps.
*
* @var string[]
* @phpstan-var list<string>
*/
protected $helpers = ['url'];
/**
* Reads in the configuration array (described above) and stores
* the valid parts that we'll need.
*
* @return $this
*/
public function initialize(Autoload $config, Modules $modules)
{
$this->prefixes = [];
$this->classmap = [];
$this->files = [];
// We have to have one or the other, though we don't enforce the need
// to have both present in order to work.
if ($config->psr4 === [] && $config->classmap === []) {
throw new InvalidArgumentException('Config array must contain either the \'psr4\' key or the \'classmap\' key.');
}
if ($config->psr4 !== []) {
$this->addNamespace($config->psr4);
}
if ($config->classmap !== []) {
$this->classmap = $config->classmap;
}
if ($config->files !== []) {
$this->files = $config->files;
}
if (isset($config->helpers)) { // @phpstan-ignore-line
$this->helpers = [...$this->helpers, ...$config->helpers];
}
if (is_file(COMPOSER_PATH)) {
$this->loadComposerInfo($modules);
}
return $this;
}
private function loadComposerInfo(Modules $modules): void
{
/**
* @var ClassLoader $composer
*/
$composer = include COMPOSER_PATH;
$this->loadComposerClassmap($composer);
// Should we load through Composer's namespaces, also?
if ($modules->discoverInComposer) {
// @phpstan-ignore-next-line
$this->loadComposerNamespaces($composer, $modules->composerPackages ?? []);
}
unset($composer);
}
/**
* Register the loader with the SPL autoloader stack.
*
* @return void
*/
public function register()
{
// Prepend the PSR4 autoloader for maximum performance.
spl_autoload_register([$this, 'loadClass'], true, true);
// Now prepend another loader for the files in our class map.
spl_autoload_register([$this, 'loadClassmap'], true, true);
// Load our non-class files
foreach ($this->files as $file) {
$this->includeFile($file);
}
}
/**
* Unregister autoloader.
*
* This method is for testing.
*/
public function unregister(): void
{
spl_autoload_unregister([$this, 'loadClass']);
spl_autoload_unregister([$this, 'loadClassmap']);
}
/**
* Registers namespaces with the autoloader.
*
* @param array<string, array<int, string>|string>|string $namespace
* @phpstan-param array<string, list<string>|string>|string $namespace
*
* @return $this
*/
public function addNamespace($namespace, ?string $path = null)
{
if (is_array($namespace)) {
foreach ($namespace as $prefix => $namespacedPath) {
$prefix = trim($prefix, '\\');
if (is_array($namespacedPath)) {
foreach ($namespacedPath as $dir) {
$this->prefixes[$prefix][] = rtrim($dir, '\\/') . DIRECTORY_SEPARATOR;
}
continue;
}
$this->prefixes[$prefix][] = rtrim($namespacedPath, '\\/') . DIRECTORY_SEPARATOR;
}
} else {
$this->prefixes[trim($namespace, '\\')][] = rtrim($path, '\\/') . DIRECTORY_SEPARATOR;
}
return $this;
}
/**
* Get namespaces with prefixes as keys and paths as values.
*
* If a prefix param is set, returns only paths to the given prefix.
*
* @return array
*/
public function getNamespace(?string $prefix = null)
{
if ($prefix === null) {
return $this->prefixes;
}
return $this->prefixes[trim($prefix, '\\')] ?? [];
}
/**
* Removes a single namespace from the psr4 settings.
*
* @return $this
*/
public function removeNamespace(string $namespace)
{
if (isset($this->prefixes[trim($namespace, '\\')])) {
unset($this->prefixes[trim($namespace, '\\')]);
}
return $this;
}
/**
* Load a class using available class mapping.
*
* @internal For `spl_autoload_register` use.
*/
public function loadClassmap(string $class): void
{
$file = $this->classmap[$class] ?? '';
if (is_string($file) && $file !== '') {
$this->includeFile($file);
}
}
/**
* Loads the class file for a given class name.
*
* @internal For `spl_autoload_register` use.
*
* @param string $class The fully qualified class name.
*/
public function loadClass(string $class): void
{
$this->loadInNamespace($class);
}
/**
* Loads the class file for a given class name.
*
* @param string $class The fully-qualified class name
*
* @return false|string The mapped file name on success, or boolean false on fail
*/
protected function loadInNamespace(string $class)
{
if (strpos($class, '\\') === false) {
return false;
}
foreach ($this->prefixes as $namespace => $directories) {
foreach ($directories as $directory) {
$directory = rtrim($directory, '\\/');
if (strpos($class, $namespace) === 0) {
$filePath = $directory . str_replace('\\', DIRECTORY_SEPARATOR, substr($class, strlen($namespace))) . '.php';
$filename = $this->includeFile($filePath);
if ($filename) {
return $filename;
}
}
}
}
// never found a mapped file
return false;
}
/**
* A central way to include a file. Split out primarily for testing purposes.
*
* @return false|string The filename on success, false if the file is not loaded
*/
protected function includeFile(string $file)
{
if (is_file($file)) {
include_once $file;
return $file;
}
return false;
}
/**
* Check file path.
*
* Checks special characters that are illegal in filenames on certain
* operating systems and special characters requiring special escaping
* to manipulate at the command line. Replaces spaces and consecutive
* dashes with a single dash. Trim period, dash and underscore from beginning
* and end of filename.
*
* @return string The sanitized filename
*
* @deprecated No longer used. See https://github.com/codeigniter4/CodeIgniter4/issues/7055
*/
public function sanitizeFilename(string $filename): string
{
// Only allow characters deemed safe for POSIX portable filenames.
// Plus the forward slash for directory separators since this might be a path.
// http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_278
// Modified to allow backslash and colons for on Windows machines.
$result = preg_match_all('/[^0-9\p{L}\s\/\-_.:\\\\]/u', $filename, $matches);
if ($result > 0) {
$chars = implode('', $matches[0]);
throw new InvalidArgumentException(
'The file path contains special characters "' . $chars
. '" that are not allowed: "' . $filename . '"'
);
}
if ($result === false) {
if (version_compare(PHP_VERSION, '8.0.0', '>=')) {
$message = preg_last_error_msg();
} else {
$message = 'Regex error. error code: ' . preg_last_error();
}
throw new RuntimeException($message . '. filename: "' . $filename . '"');
}
// Clean up our filename edges.
$cleanFilename = trim($filename, '.-_');
if ($filename !== $cleanFilename) {
throw new InvalidArgumentException('The characters ".-_" are not allowed in filename edges: "' . $filename . '"');
}
return $cleanFilename;
}
private function loadComposerNamespaces(ClassLoader $composer, array $composerPackages): void
{
$namespacePaths = $composer->getPrefixesPsr4();
// Get rid of CodeIgniter so we don't have duplicates
if (isset($namespacePaths['CodeIgniter\\'])) {
unset($namespacePaths['CodeIgniter\\']);
}
if (! method_exists(InstalledVersions::class, 'getAllRawData')) {
throw new RuntimeException(
'Your Composer version is too old.'
. ' Please update Composer (run `composer self-update`) to v2.0.14 or later'
. ' and remove your vendor/ directory, and run `composer update`.'
);
}
// This method requires Composer 2.0.14 or later.
$allData = InstalledVersions::getAllRawData();
$packageList = [];
foreach ($allData as $list) {
$packageList = array_merge($packageList, $list['versions']);
}
// Check config for $composerPackages.
$only = $composerPackages['only'] ?? [];
$exclude = $composerPackages['exclude'] ?? [];
if ($only !== [] && $exclude !== []) {
throw new ConfigException('Cannot use "only" and "exclude" at the same time in "Config\Modules::$composerPackages".');
}
// Get install paths of packages to add namespace for auto-discovery.
$installPaths = [];
if ($only !== []) {
foreach ($packageList as $packageName => $data) {
if (in_array($packageName, $only, true) && isset($data['install_path'])) {
$installPaths[] = $data['install_path'];
}
}
} else {
foreach ($packageList as $packageName => $data) {
if (! in_array($packageName, $exclude, true) && isset($data['install_path'])) {
$installPaths[] = $data['install_path'];
}
}
}
$newPaths = [];
foreach ($namespacePaths as $namespace => $srcPaths) {
$add = false;
foreach ($srcPaths as $path) {
foreach ($installPaths as $installPath) {
if ($installPath === substr($path, 0, strlen($installPath))) {
$add = true;
break 2;
}
}
}
if ($add) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($namespace, '\\ ')] = $srcPaths;
}
}
$this->addNamespace($newPaths);
}
private function loadComposerClassmap(ClassLoader $composer): void
{
$classes = $composer->getClassMap();
$this->classmap = array_merge($this->classmap, $classes);
}
/**
* Locates autoload information from Composer, if available.
*
* @deprecated No longer used.
*
* @return void
*/
protected function discoverComposerNamespaces()
{
if (! is_file(COMPOSER_PATH)) {
return;
}
/**
* @var ClassLoader $composer
*/
$composer = include COMPOSER_PATH;
$paths = $composer->getPrefixesPsr4();
$classes = $composer->getClassMap();
unset($composer);
// Get rid of CodeIgniter so we don't have duplicates
if (isset($paths['CodeIgniter\\'])) {
unset($paths['CodeIgniter\\']);
}
$newPaths = [];
foreach ($paths as $key => $value) {
// Composer stores namespaces with trailing slash. We don't.
$newPaths[rtrim($key, '\\ ')] = $value;
}
$this->prefixes = array_merge($this->prefixes, $newPaths);
$this->classmap = array_merge($this->classmap, $classes);
}
/**
* Loads helpers
*/
public function loadHelpers(): void
{
helper($this->helpers);
}
}