4 * This file is part of Composer.
6 * (c) Nils Adermann <naderman@naderman.de>
7 * Jordi Boggiano <j.boggiano@seld.be>
9 * For the full copyright and license information, please view the LICENSE
10 * file that was distributed with this source code.
13 namespace Composer\Autoload
;
16 * ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
18 * $loader = new \Composer\Autoload\ClassLoader();
20 * // register classes with namespaces
21 * $loader->add('Symfony\Component', __DIR__.'/component');
22 * $loader->add('Symfony', __DIR__.'/framework');
24 * // activate the autoloader
25 * $loader->register();
27 * // to enable searching the include path (eg. for PEAR packages)
28 * $loader->setUseIncludePath(true);
30 * In this example, if you try to use a class in the Symfony\Component
31 * namespace or one of its children (Symfony\Component\Console for instance),
32 * the autoloader will first look for the class under the component/
33 * directory, and it will then fallback to the framework/ directory if not
34 * found before giving up.
36 * This class is loosely based on the Symfony UniversalClassLoader.
38 * @author Fabien Potencier <fabien@symfony.com>
39 * @author Jordi Boggiano <j.boggiano@seld.be>
40 * @see https://www.php-fig.org/psr/psr-0/
41 * @see https://www.php-fig.org/psr/psr-4/
51 * @psalm-var array<string, array<string, int>>
53 private $prefixLengthsPsr4 = array();
56 * @psalm-var array<string, array<int, string>>
58 private $prefixDirsPsr4 = array();
61 * @psalm-var array<string, string>
63 private $fallbackDirsPsr4 = array();
68 * @psalm-var array<string, array<string, string[]>>
70 private $prefixesPsr0 = array();
73 * @psalm-var array<string, string>
75 private $fallbackDirsPsr0 = array();
78 private $useIncludePath = false;
82 * @psalm-var array<string, string>
84 private $classMap = array();
87 private $classMapAuthoritative = false;
91 * @psalm-var array<string, bool>
93 private $missingClasses = array();
101 private static $registeredLoaders = array();
104 * @param ?string $vendorDir
106 public function __construct($vendorDir = null)
108 $this->vendorDir
= $vendorDir;
114 public function getPrefixes()
116 if (!empty($this->prefixesPsr0
)) {
117 return call_user_func_array('array_merge', array_values($this->prefixesPsr0
));
125 * @psalm-return array<string, array<int, string>>
127 public function getPrefixesPsr4()
129 return $this->prefixDirsPsr4
;
134 * @psalm-return array<string, string>
136 public function getFallbackDirs()
138 return $this->fallbackDirsPsr0
;
143 * @psalm-return array<string, string>
145 public function getFallbackDirsPsr4()
147 return $this->fallbackDirsPsr4
;
151 * @return string[] Array of classname => path
152 * @psalm-return array<string, string>
154 public function getClassMap()
156 return $this->classMap
;
160 * @param string[] $classMap Class to filename map
161 * @psalm-param array<string, string> $classMap
165 public function addClassMap(array $classMap)
167 if ($this->classMap
) {
168 $this->classMap
= array_merge($this->classMap
, $classMap);
170 $this->classMap
= $classMap;
175 * Registers a set of PSR-0 directories for a given prefix, either
176 * appending or prepending to the ones previously set for this prefix.
178 * @param string $prefix The prefix
179 * @param string[]|string $paths The PSR-0 root directories
180 * @param bool $prepend Whether to prepend the directories
184 public function add($prefix, $paths, $prepend = false)
188 $this->fallbackDirsPsr0
= array_merge(
190 $this->fallbackDirsPsr0
193 $this->fallbackDirsPsr0
= array_merge(
194 $this->fallbackDirsPsr0
,
203 if (!isset($this->prefixesPsr0
[$first][$prefix])) {
204 $this->prefixesPsr0
[$first][$prefix] = (array) $paths;
209 $this->prefixesPsr0
[$first][$prefix] = array_merge(
211 $this->prefixesPsr0
[$first][$prefix]
214 $this->prefixesPsr0
[$first][$prefix] = array_merge(
215 $this->prefixesPsr0
[$first][$prefix],
222 * Registers a set of PSR-4 directories for a given namespace, either
223 * appending or prepending to the ones previously set for this namespace.
225 * @param string $prefix The prefix/namespace, with trailing '\\'
226 * @param string[]|string $paths The PSR-4 base directories
227 * @param bool $prepend Whether to prepend the directories
229 * @throws \InvalidArgumentException
233 public function addPsr4($prefix, $paths, $prepend = false)
236 // Register directories for the root namespace.
238 $this->fallbackDirsPsr4
= array_merge(
240 $this->fallbackDirsPsr4
243 $this->fallbackDirsPsr4
= array_merge(
244 $this->fallbackDirsPsr4
,
248 } elseif (!isset($this->prefixDirsPsr4
[$prefix])) {
249 // Register directories for a new namespace.
250 $length = strlen($prefix);
251 if ('\\' !== $prefix[$length - 1]) {
252 throw new \
InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
254 $this->prefixLengthsPsr4
[$prefix[0]][$prefix] = $length;
255 $this->prefixDirsPsr4
[$prefix] = (array) $paths;
256 } elseif ($prepend) {
257 // Prepend directories for an already registered namespace.
258 $this->prefixDirsPsr4
[$prefix] = array_merge(
260 $this->prefixDirsPsr4
[$prefix]
263 // Append directories for an already registered namespace.
264 $this->prefixDirsPsr4
[$prefix] = array_merge(
265 $this->prefixDirsPsr4
[$prefix],
272 * Registers a set of PSR-0 directories for a given prefix,
273 * replacing any others previously set for this prefix.
275 * @param string $prefix The prefix
276 * @param string[]|string $paths The PSR-0 base directories
280 public function set($prefix, $paths)
283 $this->fallbackDirsPsr0
= (array) $paths;
285 $this->prefixesPsr0
[$prefix[0]][$prefix] = (array) $paths;
290 * Registers a set of PSR-4 directories for a given namespace,
291 * replacing any others previously set for this namespace.
293 * @param string $prefix The prefix/namespace, with trailing '\\'
294 * @param string[]|string $paths The PSR-4 base directories
296 * @throws \InvalidArgumentException
300 public function setPsr4($prefix, $paths)
303 $this->fallbackDirsPsr4
= (array) $paths;
305 $length = strlen($prefix);
306 if ('\\' !== $prefix[$length - 1]) {
307 throw new \
InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
309 $this->prefixLengthsPsr4
[$prefix[0]][$prefix] = $length;
310 $this->prefixDirsPsr4
[$prefix] = (array) $paths;
315 * Turns on searching the include path for class files.
317 * @param bool $useIncludePath
321 public function setUseIncludePath($useIncludePath)
323 $this->useIncludePath
= $useIncludePath;
327 * Can be used to check if the autoloader uses the include path to check
332 public function getUseIncludePath()
334 return $this->useIncludePath
;
338 * Turns off searching the prefix and fallback directories for classes
339 * that have not been registered with the class map.
341 * @param bool $classMapAuthoritative
345 public function setClassMapAuthoritative($classMapAuthoritative)
347 $this->classMapAuthoritative
= $classMapAuthoritative;
351 * Should class lookup fail if not found in the current class map?
355 public function isClassMapAuthoritative()
357 return $this->classMapAuthoritative
;
361 * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
363 * @param string|null $apcuPrefix
367 public function setApcuPrefix($apcuPrefix)
369 $this->apcuPrefix
= function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN
) ?
$apcuPrefix : null;
373 * The APCu prefix in use, or null if APCu caching is not enabled.
375 * @return string|null
377 public function getApcuPrefix()
379 return $this->apcuPrefix
;
383 * Registers this instance as an autoloader.
385 * @param bool $prepend Whether to prepend the autoloader or not
389 public function register($prepend = false)
391 spl_autoload_register(array($this, 'loadClass'), true, $prepend);
393 if (null === $this->vendorDir
) {
398 self
::$registeredLoaders = array($this->vendorDir
=> $this) + self
::$registeredLoaders;
400 unset(self
::$registeredLoaders[$this->vendorDir
]);
401 self
::$registeredLoaders[$this->vendorDir
] = $this;
406 * Unregisters this instance as an autoloader.
410 public function unregister()
412 spl_autoload_unregister(array($this, 'loadClass'));
414 if (null !== $this->vendorDir
) {
415 unset(self
::$registeredLoaders[$this->vendorDir
]);
420 * Loads the given class or interface.
422 * @param string $class The name of the class
423 * @return true|null True if loaded, null otherwise
425 public function loadClass($class)
427 if ($file = $this->findFile($class)) {
437 * Finds the path to the file where the class is defined.
439 * @param string $class The name of the class
441 * @return string|false The path if found, false otherwise
443 public function findFile($class)
446 if (isset($this->classMap
[$class])) {
447 return $this->classMap
[$class];
449 if ($this->classMapAuthoritative ||
isset($this->missingClasses
[$class])) {
452 if (null !== $this->apcuPrefix
) {
453 $file = apcu_fetch($this->apcuPrefix
.$class, $hit);
459 $file = $this->findFileWithExtension($class, '.php');
461 // Search for Hack files if we are running on HHVM
462 if (false === $file && defined('HHVM_VERSION')) {
463 $file = $this->findFileWithExtension($class, '.hh');
466 if (null !== $this->apcuPrefix
) {
467 apcu_add($this->apcuPrefix
.$class, $file);
470 if (false === $file) {
471 // Remember that this class does not exist.
472 $this->missingClasses
[$class] = true;
479 * Returns the currently registered loaders indexed by their corresponding vendor directories.
483 public static function getRegisteredLoaders()
485 return self
::$registeredLoaders;
489 * @param string $class
491 * @return string|false
493 private function findFileWithExtension($class, $ext)
496 $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR
) . $ext;
499 if (isset($this->prefixLengthsPsr4
[$first])) {
501 while (false !== $lastPos = strrpos($subPath, '\\')) {
502 $subPath = substr($subPath, 0, $lastPos);
503 $search = $subPath . '\\';
504 if (isset($this->prefixDirsPsr4
[$search])) {
505 $pathEnd = DIRECTORY_SEPARATOR
. substr($logicalPathPsr4, $lastPos +
1);
506 foreach ($this->prefixDirsPsr4
[$search] as $dir) {
507 if (file_exists($file = $dir . $pathEnd)) {
515 // PSR-4 fallback dirs
516 foreach ($this->fallbackDirsPsr4
as $dir) {
517 if (file_exists($file = $dir . DIRECTORY_SEPARATOR
. $logicalPathPsr4)) {
523 if (false !== $pos = strrpos($class, '\\')) {
524 // namespaced class name
525 $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos +
1)
526 . strtr(substr($logicalPathPsr4, $pos +
1), '_', DIRECTORY_SEPARATOR
);
528 // PEAR-like class name
529 $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR
) . $ext;
532 if (isset($this->prefixesPsr0
[$first])) {
533 foreach ($this->prefixesPsr0
[$first] as $prefix => $dirs) {
534 if (0 === strpos($class, $prefix)) {
535 foreach ($dirs as $dir) {
536 if (file_exists($file = $dir . DIRECTORY_SEPARATOR
. $logicalPathPsr0)) {
544 // PSR-0 fallback dirs
545 foreach ($this->fallbackDirsPsr0
as $dir) {
546 if (file_exists($file = $dir . DIRECTORY_SEPARATOR
. $logicalPathPsr0)) {
551 // PSR-0 include paths.
552 if ($this->useIncludePath
&& $file = stream_resolve_include_path($logicalPathPsr0)) {
561 * Scope isolated include.
563 * Prevents access to $this/self from included files.
565 * @param string $file
569 function includeFile($file)