ClassLoader.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. /*
  3. * This file is part of Composer.
  4. *
  5. * (c) Nils Adermann <naderman@naderman.de>
  6. * Jordi Boggiano <j.boggiano@seld.be>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Composer\Autoload;
  12. /**
  13. * ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
  14. *
  15. * $loader = new \Composer\Autoload\ClassLoader();
  16. *
  17. * // register classes with namespaces
  18. * $loader->add('Symfony\Component', __DIR__.'/component');
  19. * $loader->add('Symfony', __DIR__.'/framework');
  20. *
  21. * // activate the autoloader
  22. * $loader->register();
  23. *
  24. * // to enable searching the include path (eg. for PEAR packages)
  25. * $loader->setUseIncludePath(true);
  26. *
  27. * In this example, if you try to use a class in the Symfony\Component
  28. * namespace or one of its children (Symfony\Component\Console for instance),
  29. * the autoloader will first look for the class under the component/
  30. * directory, and it will then fallback to the framework/ directory if not
  31. * found before giving up.
  32. *
  33. * This class is loosely based on the Symfony UniversalClassLoader.
  34. *
  35. * @author Fabien Potencier <fabien@symfony.com>
  36. * @author Jordi Boggiano <j.boggiano@seld.be>
  37. * @see https://www.php-fig.org/psr/psr-0/
  38. * @see https://www.php-fig.org/psr/psr-4/
  39. */
  40. class ClassLoader
  41. {
  42. private $vendorDir;
  43. // PSR-4
  44. private $prefixLengthsPsr4 = array();
  45. private $prefixDirsPsr4 = array();
  46. private $fallbackDirsPsr4 = array();
  47. // PSR-0
  48. private $prefixesPsr0 = array();
  49. private $fallbackDirsPsr0 = array();
  50. private $useIncludePath = false;
  51. private $classMap = array();
  52. private $classMapAuthoritative = false;
  53. private $missingClasses = array();
  54. private $apcuPrefix;
  55. private static $registeredLoaders = array();
  56. public function __construct($vendorDir = null)
  57. {
  58. $this->vendorDir = $vendorDir;
  59. }
  60. public function getPrefixes()
  61. {
  62. if (!empty($this->prefixesPsr0)) {
  63. return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
  64. }
  65. return array();
  66. }
  67. public function getPrefixesPsr4()
  68. {
  69. return $this->prefixDirsPsr4;
  70. }
  71. public function getFallbackDirs()
  72. {
  73. return $this->fallbackDirsPsr0;
  74. }
  75. public function getFallbackDirsPsr4()
  76. {
  77. return $this->fallbackDirsPsr4;
  78. }
  79. public function getClassMap()
  80. {
  81. return $this->classMap;
  82. }
  83. /**
  84. * @param array $classMap Class to filename map
  85. */
  86. public function addClassMap(array $classMap)
  87. {
  88. if ($this->classMap) {
  89. $this->classMap = array_merge($this->classMap, $classMap);
  90. } else {
  91. $this->classMap = $classMap;
  92. }
  93. }
  94. /**
  95. * Registers a set of PSR-0 directories for a given prefix, either
  96. * appending or prepending to the ones previously set for this prefix.
  97. *
  98. * @param string $prefix The prefix
  99. * @param array|string $paths The PSR-0 root directories
  100. * @param bool $prepend Whether to prepend the directories
  101. */
  102. public function add($prefix, $paths, $prepend = false)
  103. {
  104. if (!$prefix) {
  105. if ($prepend) {
  106. $this->fallbackDirsPsr0 = array_merge(
  107. (array) $paths,
  108. $this->fallbackDirsPsr0
  109. );
  110. } else {
  111. $this->fallbackDirsPsr0 = array_merge(
  112. $this->fallbackDirsPsr0,
  113. (array) $paths
  114. );
  115. }
  116. return;
  117. }
  118. $first = $prefix[0];
  119. if (!isset($this->prefixesPsr0[$first][$prefix])) {
  120. $this->prefixesPsr0[$first][$prefix] = (array) $paths;
  121. return;
  122. }
  123. if ($prepend) {
  124. $this->prefixesPsr0[$first][$prefix] = array_merge(
  125. (array) $paths,
  126. $this->prefixesPsr0[$first][$prefix]
  127. );
  128. } else {
  129. $this->prefixesPsr0[$first][$prefix] = array_merge(
  130. $this->prefixesPsr0[$first][$prefix],
  131. (array) $paths
  132. );
  133. }
  134. }
  135. /**
  136. * Registers a set of PSR-4 directories for a given namespace, either
  137. * appending or prepending to the ones previously set for this namespace.
  138. *
  139. * @param string $prefix The prefix/namespace, with trailing '\\'
  140. * @param array|string $paths The PSR-4 base directories
  141. * @param bool $prepend Whether to prepend the directories
  142. *
  143. * @throws \InvalidArgumentException
  144. */
  145. public function addPsr4($prefix, $paths, $prepend = false)
  146. {
  147. if (!$prefix) {
  148. // Register directories for the root namespace.
  149. if ($prepend) {
  150. $this->fallbackDirsPsr4 = array_merge(
  151. (array) $paths,
  152. $this->fallbackDirsPsr4
  153. );
  154. } else {
  155. $this->fallbackDirsPsr4 = array_merge(
  156. $this->fallbackDirsPsr4,
  157. (array) $paths
  158. );
  159. }
  160. } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
  161. // Register directories for a new namespace.
  162. $length = strlen($prefix);
  163. if ('\\' !== $prefix[$length - 1]) {
  164. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  165. }
  166. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  167. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  168. } elseif ($prepend) {
  169. // Prepend directories for an already registered namespace.
  170. $this->prefixDirsPsr4[$prefix] = array_merge(
  171. (array) $paths,
  172. $this->prefixDirsPsr4[$prefix]
  173. );
  174. } else {
  175. // Append directories for an already registered namespace.
  176. $this->prefixDirsPsr4[$prefix] = array_merge(
  177. $this->prefixDirsPsr4[$prefix],
  178. (array) $paths
  179. );
  180. }
  181. }
  182. /**
  183. * Registers a set of PSR-0 directories for a given prefix,
  184. * replacing any others previously set for this prefix.
  185. *
  186. * @param string $prefix The prefix
  187. * @param array|string $paths The PSR-0 base directories
  188. */
  189. public function set($prefix, $paths)
  190. {
  191. if (!$prefix) {
  192. $this->fallbackDirsPsr0 = (array) $paths;
  193. } else {
  194. $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
  195. }
  196. }
  197. /**
  198. * Registers a set of PSR-4 directories for a given namespace,
  199. * replacing any others previously set for this namespace.
  200. *
  201. * @param string $prefix The prefix/namespace, with trailing '\\'
  202. * @param array|string $paths The PSR-4 base directories
  203. *
  204. * @throws \InvalidArgumentException
  205. */
  206. public function setPsr4($prefix, $paths)
  207. {
  208. if (!$prefix) {
  209. $this->fallbackDirsPsr4 = (array) $paths;
  210. } else {
  211. $length = strlen($prefix);
  212. if ('\\' !== $prefix[$length - 1]) {
  213. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  214. }
  215. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  216. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  217. }
  218. }
  219. /**
  220. * Turns on searching the include path for class files.
  221. *
  222. * @param bool $useIncludePath
  223. */
  224. public function setUseIncludePath($useIncludePath)
  225. {
  226. $this->useIncludePath = $useIncludePath;
  227. }
  228. /**
  229. * Can be used to check if the autoloader uses the include path to check
  230. * for classes.
  231. *
  232. * @return bool
  233. */
  234. public function getUseIncludePath()
  235. {
  236. return $this->useIncludePath;
  237. }
  238. /**
  239. * Turns off searching the prefix and fallback directories for classes
  240. * that have not been registered with the class map.
  241. *
  242. * @param bool $classMapAuthoritative
  243. */
  244. public function setClassMapAuthoritative($classMapAuthoritative)
  245. {
  246. $this->classMapAuthoritative = $classMapAuthoritative;
  247. }
  248. /**
  249. * Should class lookup fail if not found in the current class map?
  250. *
  251. * @return bool
  252. */
  253. public function isClassMapAuthoritative()
  254. {
  255. return $this->classMapAuthoritative;
  256. }
  257. /**
  258. * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
  259. *
  260. * @param string|null $apcuPrefix
  261. */
  262. public function setApcuPrefix($apcuPrefix)
  263. {
  264. $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
  265. }
  266. /**
  267. * The APCu prefix in use, or null if APCu caching is not enabled.
  268. *
  269. * @return string|null
  270. */
  271. public function getApcuPrefix()
  272. {
  273. return $this->apcuPrefix;
  274. }
  275. /**
  276. * Registers this instance as an autoloader.
  277. *
  278. * @param bool $prepend Whether to prepend the autoloader or not
  279. */
  280. public function register($prepend = false)
  281. {
  282. spl_autoload_register(array($this, 'loadClass'), true, $prepend);
  283. if (null === $this->vendorDir) {
  284. //no-op
  285. } elseif ($prepend) {
  286. self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
  287. } else {
  288. unset(self::$registeredLoaders[$this->vendorDir]);
  289. self::$registeredLoaders[$this->vendorDir] = $this;
  290. }
  291. }
  292. /**
  293. * Unregisters this instance as an autoloader.
  294. */
  295. public function unregister()
  296. {
  297. spl_autoload_unregister(array($this, 'loadClass'));
  298. if (null !== $this->vendorDir) {
  299. unset(self::$registeredLoaders[$this->vendorDir]);
  300. }
  301. }
  302. /**
  303. * Loads the given class or interface.
  304. *
  305. * @param string $class The name of the class
  306. * @return bool|null True if loaded, null otherwise
  307. */
  308. public function loadClass($class)
  309. {
  310. if ($file = $this->findFile($class)) {
  311. includeFile($file);
  312. return true;
  313. }
  314. }
  315. /**
  316. * Finds the path to the file where the class is defined.
  317. *
  318. * @param string $class The name of the class
  319. *
  320. * @return string|false The path if found, false otherwise
  321. */
  322. public function findFile($class)
  323. {
  324. // class map lookup
  325. if (isset($this->classMap[$class])) {
  326. return $this->classMap[$class];
  327. }
  328. if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
  329. return false;
  330. }
  331. if (null !== $this->apcuPrefix) {
  332. $file = apcu_fetch($this->apcuPrefix.$class, $hit);
  333. if ($hit) {
  334. return $file;
  335. }
  336. }
  337. $file = $this->findFileWithExtension($class, '.php');
  338. // Search for Hack files if we are running on HHVM
  339. if (false === $file && defined('HHVM_VERSION')) {
  340. $file = $this->findFileWithExtension($class, '.hh');
  341. }
  342. if (null !== $this->apcuPrefix) {
  343. apcu_add($this->apcuPrefix.$class, $file);
  344. }
  345. if (false === $file) {
  346. // Remember that this class does not exist.
  347. $this->missingClasses[$class] = true;
  348. }
  349. return $file;
  350. }
  351. /**
  352. * Returns the currently registered loaders indexed by their corresponding vendor directories.
  353. *
  354. * @return self[]
  355. */
  356. public static function getRegisteredLoaders()
  357. {
  358. return self::$registeredLoaders;
  359. }
  360. private function findFileWithExtension($class, $ext)
  361. {
  362. // PSR-4 lookup
  363. $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
  364. $first = $class[0];
  365. if (isset($this->prefixLengthsPsr4[$first])) {
  366. $subPath = $class;
  367. while (false !== $lastPos = strrpos($subPath, '\\')) {
  368. $subPath = substr($subPath, 0, $lastPos);
  369. $search = $subPath . '\\';
  370. if (isset($this->prefixDirsPsr4[$search])) {
  371. $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
  372. foreach ($this->prefixDirsPsr4[$search] as $dir) {
  373. if (file_exists($file = $dir . $pathEnd)) {
  374. return $file;
  375. }
  376. }
  377. }
  378. }
  379. }
  380. // PSR-4 fallback dirs
  381. foreach ($this->fallbackDirsPsr4 as $dir) {
  382. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
  383. return $file;
  384. }
  385. }
  386. // PSR-0 lookup
  387. if (false !== $pos = strrpos($class, '\\')) {
  388. // namespaced class name
  389. $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
  390. . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
  391. } else {
  392. // PEAR-like class name
  393. $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
  394. }
  395. if (isset($this->prefixesPsr0[$first])) {
  396. foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
  397. if (0 === strpos($class, $prefix)) {
  398. foreach ($dirs as $dir) {
  399. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  400. return $file;
  401. }
  402. }
  403. }
  404. }
  405. }
  406. // PSR-0 fallback dirs
  407. foreach ($this->fallbackDirsPsr0 as $dir) {
  408. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  409. return $file;
  410. }
  411. }
  412. // PSR-0 include paths.
  413. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
  414. return $file;
  415. }
  416. return false;
  417. }
  418. }
  419. /**
  420. * Scope isolated include.
  421. *
  422. * Prevents access to $this/self from included files.
  423. */
  424. function includeFile($file)
  425. {
  426. include $file;
  427. }