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/
48 private $prefixLengthsPsr4 = array();
49 private $prefixDirsPsr4 = array();
50 private $fallbackDirsPsr4 = array();
53 private $prefixesPsr0 = array();
54 private $fallbackDirsPsr0 = array();
56 private $useIncludePath = false;
57 private $classMap = array();
58 private $classMapAuthoritative = false;
59 private $missingClasses = array();
62 private static $registeredLoaders = array();
64 public function __construct($vendorDir = null)
66 $this->vendorDir = $vendorDir;
69 public function getPrefixes()
71 if (!empty($this->prefixesPsr0)) {
72 return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
78 public function getPrefixesPsr4()
80 return $this->prefixDirsPsr4;
83 public function getFallbackDirs()
85 return $this->fallbackDirsPsr0;
88 public function getFallbackDirsPsr4()
90 return $this->fallbackDirsPsr4;
93 public function getClassMap()
95 return $this->classMap;
99 * @param array $classMap Class to filename map
101 public function addClassMap(array $classMap)
103 if ($this->classMap) {
104 $this->classMap = array_merge($this->classMap, $classMap);
106 $this->classMap = $classMap;
111 * Registers a set of PSR-0 directories for a given prefix, either
112 * appending or prepending to the ones previously set for this prefix.
114 * @param string $prefix The prefix
115 * @param array|string $paths The PSR-0 root directories
116 * @param bool $prepend Whether to prepend the directories
118 public function add($prefix, $paths, $prepend = false)
122 $this->fallbackDirsPsr0 = array_merge(
124 $this->fallbackDirsPsr0
127 $this->fallbackDirsPsr0 = array_merge(
128 $this->fallbackDirsPsr0,
137 if (!isset($this->prefixesPsr0[$first][$prefix])) {
138 $this->prefixesPsr0[$first][$prefix] = (array) $paths;
143 $this->prefixesPsr0[$first][$prefix] = array_merge(
145 $this->prefixesPsr0[$first][$prefix]
148 $this->prefixesPsr0[$first][$prefix] = array_merge(
149 $this->prefixesPsr0[$first][$prefix],
156 * Registers a set of PSR-4 directories for a given namespace, either
157 * appending or prepending to the ones previously set for this namespace.
159 * @param string $prefix The prefix/namespace, with trailing '\\'
160 * @param array|string $paths The PSR-4 base directories
161 * @param bool $prepend Whether to prepend the directories
163 * @throws \InvalidArgumentException
165 public function addPsr4($prefix, $paths, $prepend = false)
168 // Register directories for the root namespace.
170 $this->fallbackDirsPsr4 = array_merge(
172 $this->fallbackDirsPsr4
175 $this->fallbackDirsPsr4 = array_merge(
176 $this->fallbackDirsPsr4,
180 } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
181 // Register directories for a new namespace.
182 $length = strlen($prefix);
183 if ('\\' !== $prefix[$length - 1]) {
184 throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
186 $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
187 $this->prefixDirsPsr4[$prefix] = (array) $paths;
188 } elseif ($prepend) {
189 // Prepend directories for an already registered namespace.
190 $this->prefixDirsPsr4[$prefix] = array_merge(
192 $this->prefixDirsPsr4[$prefix]
195 // Append directories for an already registered namespace.
196 $this->prefixDirsPsr4[$prefix] = array_merge(
197 $this->prefixDirsPsr4[$prefix],
204 * Registers a set of PSR-0 directories for a given prefix,
205 * replacing any others previously set for this prefix.
207 * @param string $prefix The prefix
208 * @param array|string $paths The PSR-0 base directories
210 public function set($prefix, $paths)
213 $this->fallbackDirsPsr0 = (array) $paths;
215 $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
220 * Registers a set of PSR-4 directories for a given namespace,
221 * replacing any others previously set for this namespace.
223 * @param string $prefix The prefix/namespace, with trailing '\\'
224 * @param array|string $paths The PSR-4 base directories
226 * @throws \InvalidArgumentException
228 public function setPsr4($prefix, $paths)
231 $this->fallbackDirsPsr4 = (array) $paths;
233 $length = strlen($prefix);
234 if ('\\' !== $prefix[$length - 1]) {
235 throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
237 $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
238 $this->prefixDirsPsr4[$prefix] = (array) $paths;
243 * Turns on searching the include path for class files.
245 * @param bool $useIncludePath
247 public function setUseIncludePath($useIncludePath)
249 $this->useIncludePath = $useIncludePath;
253 * Can be used to check if the autoloader uses the include path to check
258 public function getUseIncludePath()
260 return $this->useIncludePath;
264 * Turns off searching the prefix and fallback directories for classes
265 * that have not been registered with the class map.
267 * @param bool $classMapAuthoritative
269 public function setClassMapAuthoritative($classMapAuthoritative)
271 $this->classMapAuthoritative = $classMapAuthoritative;
275 * Should class lookup fail if not found in the current class map?
279 public function isClassMapAuthoritative()
281 return $this->classMapAuthoritative;
285 * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
287 * @param string|null $apcuPrefix
289 public function setApcuPrefix($apcuPrefix)
291 $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
295 * The APCu prefix in use, or null if APCu caching is not enabled.
297 * @return string|null
299 public function getApcuPrefix()
301 return $this->apcuPrefix;
305 * Registers this instance as an autoloader.
307 * @param bool $prepend Whether to prepend the autoloader or not
309 public function register($prepend = false)
311 spl_autoload_register(array($this, 'loadClass'), true, $prepend);
313 if (null === $this->vendorDir) {
318 self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
320 unset(self::$registeredLoaders[$this->vendorDir]);
321 self::$registeredLoaders[$this->vendorDir] = $this;
326 * Unregisters this instance as an autoloader.
328 public function unregister()
330 spl_autoload_unregister(array($this, 'loadClass'));
332 if (null !== $this->vendorDir) {
333 unset(self::$registeredLoaders[$this->vendorDir]);
338 * Loads the given class or interface.
340 * @param string $class The name of the class
341 * @return bool|null True if loaded, null otherwise
343 public function loadClass($class)
345 if ($file = $this->findFile($class)) {
353 * Finds the path to the file where the class is defined.
355 * @param string $class The name of the class
357 * @return string|false The path if found, false otherwise
359 public function findFile($class)
362 if (isset($this->classMap[$class])) {
363 return $this->classMap[$class];
365 if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
368 if (null !== $this->apcuPrefix) {
369 $file = apcu_fetch($this->apcuPrefix.$class, $hit);
375 $file = $this->findFileWithExtension($class, '.php');
377 // Search for Hack files if we are running on HHVM
378 if (false === $file && defined('HHVM_VERSION')) {
379 $file = $this->findFileWithExtension($class, '.hh');
382 if (null !== $this->apcuPrefix) {
383 apcu_add($this->apcuPrefix.$class, $file);
386 if (false === $file) {
387 // Remember that this class does not exist.
388 $this->missingClasses[$class] = true;
395 * Returns the currently registered loaders indexed by their corresponding vendor directories.
399 public static function getRegisteredLoaders()
401 return self::$registeredLoaders;
404 private function findFileWithExtension($class, $ext)
407 $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
410 if (isset($this->prefixLengthsPsr4[$first])) {
412 while (false !== $lastPos = strrpos($subPath, '\\')) {
413 $subPath = substr($subPath, 0, $lastPos);
414 $search = $subPath . '\\';
415 if (isset($this->prefixDirsPsr4[$search])) {
416 $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
417 foreach ($this->prefixDirsPsr4[$search] as $dir) {
418 if (file_exists($file = $dir . $pathEnd)) {
426 // PSR-4 fallback dirs
427 foreach ($this->fallbackDirsPsr4 as $dir) {
428 if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
434 if (false !== $pos = strrpos($class, '\\')) {
435 // namespaced class name
436 $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
437 . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
439 // PEAR-like class name
440 $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
443 if (isset($this->prefixesPsr0[$first])) {
444 foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
445 if (0 === strpos($class, $prefix)) {
446 foreach ($dirs as $dir) {
447 if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
455 // PSR-0 fallback dirs
456 foreach ($this->fallbackDirsPsr0 as $dir) {
457 if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
462 // PSR-0 include paths.
463 if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
472 * Scope isolated include.
474 * Prevents access to $this/self from included files.
476 function includeFile($file)