1
0

ClassLoader.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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. /** @var \Closure(string):void */
  43. private static $includeFile;
  44. /** @var ?string */
  45. private $vendorDir;
  46. // PSR-4
  47. /**
  48. * @var array[]
  49. * @psalm-var array<string, array<string, int>>
  50. */
  51. private $prefixLengthsPsr4 = array();
  52. /**
  53. * @var array[]
  54. * @psalm-var array<string, array<int, string>>
  55. */
  56. private $prefixDirsPsr4 = array();
  57. /**
  58. * @var array[]
  59. * @psalm-var array<string, string>
  60. */
  61. private $fallbackDirsPsr4 = array();
  62. // PSR-0
  63. /**
  64. * @var array[]
  65. * @psalm-var array<string, array<string, string[]>>
  66. */
  67. private $prefixesPsr0 = array();
  68. /**
  69. * @var array[]
  70. * @psalm-var array<string, string>
  71. */
  72. private $fallbackDirsPsr0 = array();
  73. /** @var bool */
  74. private $useIncludePath = false;
  75. /**
  76. * @var string[]
  77. * @psalm-var array<string, string>
  78. */
  79. private $classMap = array();
  80. /** @var bool */
  81. private $classMapAuthoritative = false;
  82. /**
  83. * @var bool[]
  84. * @psalm-var array<string, bool>
  85. */
  86. private $missingClasses = array();
  87. /** @var ?string */
  88. private $apcuPrefix;
  89. /**
  90. * @var self[]
  91. */
  92. private static $registeredLoaders = array();
  93. /**
  94. * @param ?string $vendorDir
  95. */
  96. public function __construct($vendorDir = null)
  97. {
  98. $this->vendorDir = $vendorDir;
  99. self::initializeIncludeClosure();
  100. }
  101. /**
  102. * @return string[]
  103. */
  104. public function getPrefixes()
  105. {
  106. if (!empty($this->prefixesPsr0)) {
  107. return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
  108. }
  109. return array();
  110. }
  111. /**
  112. * @return array[]
  113. * @psalm-return array<string, array<int, string>>
  114. */
  115. public function getPrefixesPsr4()
  116. {
  117. return $this->prefixDirsPsr4;
  118. }
  119. /**
  120. * @return array[]
  121. * @psalm-return array<string, string>
  122. */
  123. public function getFallbackDirs()
  124. {
  125. return $this->fallbackDirsPsr0;
  126. }
  127. /**
  128. * @return array[]
  129. * @psalm-return array<string, string>
  130. */
  131. public function getFallbackDirsPsr4()
  132. {
  133. return $this->fallbackDirsPsr4;
  134. }
  135. /**
  136. * @return string[] Array of classname => path
  137. * @psalm-return array<string, string>
  138. */
  139. public function getClassMap()
  140. {
  141. return $this->classMap;
  142. }
  143. /**
  144. * @param string[] $classMap Class to filename map
  145. * @psalm-param array<string, string> $classMap
  146. *
  147. * @return void
  148. */
  149. public function addClassMap(array $classMap)
  150. {
  151. if ($this->classMap) {
  152. $this->classMap = array_merge($this->classMap, $classMap);
  153. } else {
  154. $this->classMap = $classMap;
  155. }
  156. }
  157. /**
  158. * Registers a set of PSR-0 directories for a given prefix, either
  159. * appending or prepending to the ones previously set for this prefix.
  160. *
  161. * @param string $prefix The prefix
  162. * @param string[]|string $paths The PSR-0 root directories
  163. * @param bool $prepend Whether to prepend the directories
  164. *
  165. * @return void
  166. */
  167. public function add($prefix, $paths, $prepend = false)
  168. {
  169. if (!$prefix) {
  170. if ($prepend) {
  171. $this->fallbackDirsPsr0 = array_merge(
  172. (array) $paths,
  173. $this->fallbackDirsPsr0
  174. );
  175. } else {
  176. $this->fallbackDirsPsr0 = array_merge(
  177. $this->fallbackDirsPsr0,
  178. (array) $paths
  179. );
  180. }
  181. return;
  182. }
  183. $first = $prefix[0];
  184. if (!isset($this->prefixesPsr0[$first][$prefix])) {
  185. $this->prefixesPsr0[$first][$prefix] = (array) $paths;
  186. return;
  187. }
  188. if ($prepend) {
  189. $this->prefixesPsr0[$first][$prefix] = array_merge(
  190. (array) $paths,
  191. $this->prefixesPsr0[$first][$prefix]
  192. );
  193. } else {
  194. $this->prefixesPsr0[$first][$prefix] = array_merge(
  195. $this->prefixesPsr0[$first][$prefix],
  196. (array) $paths
  197. );
  198. }
  199. }
  200. /**
  201. * Registers a set of PSR-4 directories for a given namespace, either
  202. * appending or prepending to the ones previously set for this namespace.
  203. *
  204. * @param string $prefix The prefix/namespace, with trailing '\\'
  205. * @param string[]|string $paths The PSR-4 base directories
  206. * @param bool $prepend Whether to prepend the directories
  207. *
  208. * @throws \InvalidArgumentException
  209. *
  210. * @return void
  211. */
  212. public function addPsr4($prefix, $paths, $prepend = false)
  213. {
  214. if (!$prefix) {
  215. // Register directories for the root namespace.
  216. if ($prepend) {
  217. $this->fallbackDirsPsr4 = array_merge(
  218. (array) $paths,
  219. $this->fallbackDirsPsr4
  220. );
  221. } else {
  222. $this->fallbackDirsPsr4 = array_merge(
  223. $this->fallbackDirsPsr4,
  224. (array) $paths
  225. );
  226. }
  227. } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
  228. // Register directories for a new namespace.
  229. $length = strlen($prefix);
  230. if ('\\' !== $prefix[$length - 1]) {
  231. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  232. }
  233. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  234. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  235. } elseif ($prepend) {
  236. // Prepend directories for an already registered namespace.
  237. $this->prefixDirsPsr4[$prefix] = array_merge(
  238. (array) $paths,
  239. $this->prefixDirsPsr4[$prefix]
  240. );
  241. } else {
  242. // Append directories for an already registered namespace.
  243. $this->prefixDirsPsr4[$prefix] = array_merge(
  244. $this->prefixDirsPsr4[$prefix],
  245. (array) $paths
  246. );
  247. }
  248. }
  249. /**
  250. * Registers a set of PSR-0 directories for a given prefix,
  251. * replacing any others previously set for this prefix.
  252. *
  253. * @param string $prefix The prefix
  254. * @param string[]|string $paths The PSR-0 base directories
  255. *
  256. * @return void
  257. */
  258. public function set($prefix, $paths)
  259. {
  260. if (!$prefix) {
  261. $this->fallbackDirsPsr0 = (array) $paths;
  262. } else {
  263. $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
  264. }
  265. }
  266. /**
  267. * Registers a set of PSR-4 directories for a given namespace,
  268. * replacing any others previously set for this namespace.
  269. *
  270. * @param string $prefix The prefix/namespace, with trailing '\\'
  271. * @param string[]|string $paths The PSR-4 base directories
  272. *
  273. * @throws \InvalidArgumentException
  274. *
  275. * @return void
  276. */
  277. public function setPsr4($prefix, $paths)
  278. {
  279. if (!$prefix) {
  280. $this->fallbackDirsPsr4 = (array) $paths;
  281. } else {
  282. $length = strlen($prefix);
  283. if ('\\' !== $prefix[$length - 1]) {
  284. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  285. }
  286. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  287. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  288. }
  289. }
  290. /**
  291. * Turns on searching the include path for class files.
  292. *
  293. * @param bool $useIncludePath
  294. *
  295. * @return void
  296. */
  297. public function setUseIncludePath($useIncludePath)
  298. {
  299. $this->useIncludePath = $useIncludePath;
  300. }
  301. /**
  302. * Can be used to check if the autoloader uses the include path to check
  303. * for classes.
  304. *
  305. * @return bool
  306. */
  307. public function getUseIncludePath()
  308. {
  309. return $this->useIncludePath;
  310. }
  311. /**
  312. * Turns off searching the prefix and fallback directories for classes
  313. * that have not been registered with the class map.
  314. *
  315. * @param bool $classMapAuthoritative
  316. *
  317. * @return void
  318. */
  319. public function setClassMapAuthoritative($classMapAuthoritative)
  320. {
  321. $this->classMapAuthoritative = $classMapAuthoritative;
  322. }
  323. /**
  324. * Should class lookup fail if not found in the current class map?
  325. *
  326. * @return bool
  327. */
  328. public function isClassMapAuthoritative()
  329. {
  330. return $this->classMapAuthoritative;
  331. }
  332. /**
  333. * APCu prefix to use to cache found/not-found classes, if the extension is enabled.
  334. *
  335. * @param string|null $apcuPrefix
  336. *
  337. * @return void
  338. */
  339. public function setApcuPrefix($apcuPrefix)
  340. {
  341. $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null;
  342. }
  343. /**
  344. * The APCu prefix in use, or null if APCu caching is not enabled.
  345. *
  346. * @return string|null
  347. */
  348. public function getApcuPrefix()
  349. {
  350. return $this->apcuPrefix;
  351. }
  352. /**
  353. * Registers this instance as an autoloader.
  354. *
  355. * @param bool $prepend Whether to prepend the autoloader or not
  356. *
  357. * @return void
  358. */
  359. public function register($prepend = false)
  360. {
  361. spl_autoload_register(array($this, 'loadClass'), true, $prepend);
  362. if (null === $this->vendorDir) {
  363. return;
  364. }
  365. if ($prepend) {
  366. self::$registeredLoaders = array($this->vendorDir => $this) + self::$registeredLoaders;
  367. } else {
  368. unset(self::$registeredLoaders[$this->vendorDir]);
  369. self::$registeredLoaders[$this->vendorDir] = $this;
  370. }
  371. }
  372. /**
  373. * Unregisters this instance as an autoloader.
  374. *
  375. * @return void
  376. */
  377. public function unregister()
  378. {
  379. spl_autoload_unregister(array($this, 'loadClass'));
  380. if (null !== $this->vendorDir) {
  381. unset(self::$registeredLoaders[$this->vendorDir]);
  382. }
  383. }
  384. /**
  385. * Loads the given class or interface.
  386. *
  387. * @param string $class The name of the class
  388. * @return true|null True if loaded, null otherwise
  389. */
  390. public function loadClass($class)
  391. {
  392. if ($file = $this->findFile($class)) {
  393. $includeFile = self::$includeFile;
  394. $includeFile($file);
  395. return true;
  396. }
  397. return null;
  398. }
  399. /**
  400. * Finds the path to the file where the class is defined.
  401. *
  402. * @param string $class The name of the class
  403. *
  404. * @return string|false The path if found, false otherwise
  405. */
  406. public function findFile($class)
  407. {
  408. // class map lookup
  409. if (isset($this->classMap[$class])) {
  410. return $this->classMap[$class];
  411. }
  412. if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
  413. return false;
  414. }
  415. if (null !== $this->apcuPrefix) {
  416. $file = apcu_fetch($this->apcuPrefix.$class, $hit);
  417. if ($hit) {
  418. return $file;
  419. }
  420. }
  421. $file = $this->findFileWithExtension($class, '.php');
  422. // Search for Hack files if we are running on HHVM
  423. if (false === $file && defined('HHVM_VERSION')) {
  424. $file = $this->findFileWithExtension($class, '.hh');
  425. }
  426. if (null !== $this->apcuPrefix) {
  427. apcu_add($this->apcuPrefix.$class, $file);
  428. }
  429. if (false === $file) {
  430. // Remember that this class does not exist.
  431. $this->missingClasses[$class] = true;
  432. }
  433. return $file;
  434. }
  435. /**
  436. * Returns the currently registered loaders indexed by their corresponding vendor directories.
  437. *
  438. * @return self[]
  439. */
  440. public static function getRegisteredLoaders()
  441. {
  442. return self::$registeredLoaders;
  443. }
  444. /**
  445. * @param string $class
  446. * @param string $ext
  447. * @return string|false
  448. */
  449. private function findFileWithExtension($class, $ext)
  450. {
  451. // PSR-4 lookup
  452. $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
  453. $first = $class[0];
  454. if (isset($this->prefixLengthsPsr4[$first])) {
  455. $subPath = $class;
  456. while (false !== $lastPos = strrpos($subPath, '\\')) {
  457. $subPath = substr($subPath, 0, $lastPos);
  458. $search = $subPath . '\\';
  459. if (isset($this->prefixDirsPsr4[$search])) {
  460. $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
  461. foreach ($this->prefixDirsPsr4[$search] as $dir) {
  462. if (file_exists($file = $dir . $pathEnd)) {
  463. return $file;
  464. }
  465. }
  466. }
  467. }
  468. }
  469. // PSR-4 fallback dirs
  470. foreach ($this->fallbackDirsPsr4 as $dir) {
  471. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
  472. return $file;
  473. }
  474. }
  475. // PSR-0 lookup
  476. if (false !== $pos = strrpos($class, '\\')) {
  477. // namespaced class name
  478. $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
  479. . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
  480. } else {
  481. // PEAR-like class name
  482. $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
  483. }
  484. if (isset($this->prefixesPsr0[$first])) {
  485. foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
  486. if (0 === strpos($class, $prefix)) {
  487. foreach ($dirs as $dir) {
  488. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  489. return $file;
  490. }
  491. }
  492. }
  493. }
  494. }
  495. // PSR-0 fallback dirs
  496. foreach ($this->fallbackDirsPsr0 as $dir) {
  497. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  498. return $file;
  499. }
  500. }
  501. // PSR-0 include paths.
  502. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
  503. return $file;
  504. }
  505. return false;
  506. }
  507. /**
  508. * @return void
  509. */
  510. private static function initializeIncludeClosure()
  511. {
  512. if (self::$includeFile !== null) {
  513. return;
  514. }
  515. /**
  516. * Scope isolated include.
  517. *
  518. * Prevents access to $this/self from included files.
  519. *
  520. * @param string $file
  521. * @return void
  522. */
  523. self::$includeFile = \Closure::bind(static function($file) {
  524. include $file;
  525. }, null, null);
  526. }
  527. }