AutoLoader.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. <?php
  2. namespace Luracast\Restler {
  3. /**
  4. * Class that implements spl_autoload facilities and multiple
  5. * conventions support.
  6. * Supports composer libraries and 100% PSR-0 compliant.
  7. * In addition we enable namespace prefixing and class aliases.
  8. *
  9. * @category Framework
  10. * @package Restler
  11. * @subpackage helper
  12. * @author Nick Lombard <github@jigsoft.co.za>
  13. * @copyright 2012 Luracast
  14. *
  15. */
  16. class AutoLoader
  17. {
  18. protected static $instance, // the singleton instance reference
  19. $perfectLoaders, // used to keep the ideal list of loaders
  20. $rogueLoaders = array(), // other auto loaders now unregistered
  21. $classMap = array(), // the class to include file mapping
  22. $aliases = array( // aliases and prefixes instead of null list aliases
  23. 'Luracast\\Restler' => null,
  24. 'Luracast\\Restler\\Format' => null,
  25. 'Luracast\\Restler\\Data' => null,
  26. 'Luracast\\Restler\\Filter' => null,
  27. );
  28. /**
  29. * Singleton instance facility.
  30. *
  31. * @static
  32. * @return AutoLoader the current instance or new instance if none exists.
  33. */
  34. public static function instance()
  35. {
  36. static::$instance = static::$instance ?: new static();
  37. return static::thereCanBeOnlyOne();
  38. }
  39. /**
  40. * Helper function to add a path to the include path.
  41. * AutoLoader uses the include path to discover classes.
  42. *
  43. * @static
  44. *
  45. * @param $path string absolute or relative path.
  46. *
  47. * @return bool false if the path cannot be resolved
  48. * or the resolved absolute path.
  49. */
  50. public static function addPath($path) {
  51. if (false === $path = stream_resolve_include_path($path))
  52. return false;
  53. else
  54. set_include_path($path.PATH_SEPARATOR.get_include_path());
  55. return $path;
  56. }
  57. /**
  58. * Other autoLoaders interfere and cause duplicate class loading.
  59. * AutoLoader is capable enough to handle all standards so no need
  60. * for others stumbling about.
  61. *
  62. * @return callable the one true auto loader.
  63. */
  64. public static function thereCanBeOnlyOne() {
  65. if (static::$perfectLoaders === spl_autoload_functions())
  66. return static::$instance;
  67. if (false !== $loaders = spl_autoload_functions())
  68. if (0 < $count = count($loaders))
  69. for ($i = 0, static::$rogueLoaders += $loaders;
  70. $i < $count && false != ($loader = $loaders[$i]);
  71. $i++)
  72. if ($loader !== static::$perfectLoaders[0])
  73. spl_autoload_unregister($loader);
  74. return static::$instance;
  75. }
  76. /**
  77. * Seen this before cache handler.
  78. * Facilitates both lookup and persist operations as well as convenience,
  79. * load complete map functionality. The key can only be given a non falsy
  80. * value once, this will be truthy for life.
  81. *
  82. * @param $key mixed class name considered or a collection of
  83. * classMap entries
  84. * @param $value mixed optional not required when doing a query on
  85. * key. Default is false we haven't seen this
  86. * class. Most of the time it will be the filename
  87. * for include and is set to true if we are unable
  88. * to load this class iow true == it does not exist.
  89. * value may also be a callable auto loader function.
  90. *
  91. * @return mixed The known value for the key or false if key has no value
  92. */
  93. public static function seen($key, $value = false)
  94. {
  95. if (is_array($key)) {
  96. static::$classMap = $key + static::$classMap;
  97. return false;
  98. }
  99. if (empty(static::$classMap[$key]))
  100. static::$classMap[$key] = $value;
  101. if (is_string($alias = static::$classMap[$key]))
  102. if (isset(static::$classMap[$alias]))
  103. return static::$classMap[$alias];
  104. return static::$classMap[$key];
  105. }
  106. /**
  107. * Protected constructor to enforce singleton pattern.
  108. * Populate a default include path.
  109. * All possible includes cant possibly be catered for and if you
  110. * require another path then simply add it calling set_include_path.
  111. */
  112. protected function __construct()
  113. {
  114. static::$perfectLoaders = array($this);
  115. if (false === static::seen('__include_path')) {
  116. $paths = explode(PATH_SEPARATOR, get_include_path());
  117. $slash = DIRECTORY_SEPARATOR;
  118. $dir = dirname(__DIR__);
  119. $source_dir = dirname($dir);
  120. $dir = dirname($source_dir);
  121. foreach (
  122. array(
  123. array($source_dir),
  124. array($dir, '..', '..', 'composer'),
  125. array($dir, 'vendor', 'composer'),
  126. array($dir, '..', '..', '..', 'php'),
  127. array($dir, 'vendor', 'php'))
  128. as $includePath)
  129. if (false !== $path = stream_resolve_include_path(
  130. implode($slash, $includePath)
  131. ))
  132. if ('composer' == end($includePath) &&
  133. false !== $classmapPath = stream_resolve_include_path(
  134. "$path{$slash}autoload_classmap.php"
  135. )
  136. ) {
  137. static::seen(static::loadFile(
  138. $classmapPath
  139. ));
  140. $paths = array_merge(
  141. $paths,
  142. array_values(static::loadFile(
  143. "$path{$slash}autoload_namespaces.php"
  144. ))
  145. );
  146. } else
  147. $paths[] = $path;
  148. $paths = array_filter(array_map(
  149. function ($path) {
  150. if (false == $realPath = @realpath($path))
  151. return null;
  152. return $realPath . DIRECTORY_SEPARATOR;
  153. },
  154. $paths
  155. ));
  156. natsort($paths);
  157. static::seen(
  158. '__include_path',
  159. implode(PATH_SEPARATOR, array_unique($paths))
  160. );
  161. }
  162. set_include_path(static::seen('__include_path'));
  163. }
  164. /**
  165. * Attempt to include the path location.
  166. * Called from a static context which will not expose the AutoLoader
  167. * instance itself.
  168. *
  169. * @param $path string location of php file on the include path
  170. *
  171. * @return bool|mixed returns reference obtained from the include or false
  172. */
  173. private static function loadFile($path)
  174. {
  175. return \Luracast_Restler_autoloaderInclude($path);
  176. }
  177. /**
  178. * Attempt to load class with namespace prefixes.
  179. *
  180. * @param $className string class name
  181. *
  182. * @return bool|mixed reference to discovered include or false
  183. */
  184. private function loadPrefixes($className)
  185. {
  186. $currentClass = $className;
  187. if (false !== $pos = strrpos($className, '\\'))
  188. $className = substr($className, $pos);
  189. else
  190. $className = "\\$className";
  191. for (
  192. $i = 0,
  193. $file = false,
  194. $count = count(static::$aliases),
  195. $prefixes = array_keys(static::$aliases);
  196. $i < $count
  197. && false === $file
  198. && false === $file = $this->discover(
  199. $variant = $prefixes[$i++].$className,
  200. $currentClass
  201. );
  202. $file = $this->loadAliases($variant)
  203. );
  204. return $file;
  205. }
  206. /**
  207. * Attempt to load configured aliases based on namespace part of class name.
  208. *
  209. * @param $className string fully qualified class name.
  210. *
  211. * @return bool|mixed reference to discovered include or false
  212. */
  213. private function loadAliases($className)
  214. {
  215. $file = false;
  216. if (preg_match('/(.+)(\\\\\w+$)/U', $className, $parts))
  217. for (
  218. $i = 0,
  219. $aliases = isset(static::$aliases[$parts[1]])
  220. ? static::$aliases[$parts[1]] : array(),
  221. $count = count($aliases);
  222. $i < $count && false === $file;
  223. $file = $this->discover(
  224. "{$aliases[$i++]}$parts[2]",
  225. $className
  226. )
  227. ) ;
  228. return $file;
  229. }
  230. /**
  231. * Load from rogueLoaders as last resort.
  232. * It may happen that a custom auto loader may load classes in a unique way,
  233. * these classes cannot be seen otherwise nor should we attempt to cover every
  234. * possible deviation. If we still can't find a class, as a last resort, we will
  235. * run through the list of rogue loaders and verify if we succeeded.
  236. *
  237. * @param $className string className that can't be found
  238. * @param null $loader callable loader optional when the loader is known
  239. *
  240. * @return bool false unless className now exists
  241. */
  242. private function loadLastResort($className, $loader = null) {
  243. $loaders = array_unique(static::$rogueLoaders, SORT_REGULAR);
  244. if (isset($loader)) {
  245. if (false === array_search($loader, $loaders))
  246. static::$rogueLoaders[] = $loader;
  247. return $this->loadThisLoader($className, $loader);
  248. }
  249. foreach ($loaders as $loader)
  250. if (false !== $file = $this->loadThisLoader($className, $loader))
  251. return $file;
  252. return false;
  253. }
  254. /**
  255. * Helper for loadLastResort.
  256. * Use loader with $className and see if className exists.
  257. *
  258. * @param $className string name of a class to load
  259. * @param $loader callable autoLoader method
  260. *
  261. * @return bool false unless className exists
  262. */
  263. private function loadThisLoader($className, $loader)
  264. {
  265. if (is_array($loader)
  266. && is_callable($loader)) {
  267. $b = new $loader[0];
  268. if (false !== $file = $b::$loader[1]($className)
  269. && $this->exists($className, $b::$loader[1])) {
  270. return $file;
  271. }
  272. } elseif (is_callable($loader)
  273. && false !== $file = $loader($className)
  274. && $this->exists($className, $loader)) {
  275. return $file;
  276. }
  277. return false;
  278. }
  279. /**
  280. * Create an alias for class.
  281. *
  282. * @param $className string the name of the alias class
  283. * @param $currentClass string the current class this alias references
  284. */
  285. private function alias($className, $currentClass)
  286. {
  287. if ($className == 'Luracast\Restler\string') return;
  288. if ($className == 'Luracast\Restler\mixed') return;
  289. if ($className != $currentClass
  290. && false !== strpos($className, $currentClass))
  291. if (!class_exists($currentClass, false)
  292. && class_alias($className, $currentClass))
  293. static::seen($currentClass, $className);
  294. }
  295. /**
  296. * Discovery process.
  297. *
  298. * @param $className string class name to discover
  299. * @param $currentClass string optional name of current class when
  300. * looking up an alias
  301. *
  302. * @return bool|mixed resolved include reference or false
  303. */
  304. private function discover($className, $currentClass = null)
  305. {
  306. $currentClass = $currentClass ?: $className;
  307. /** The short version we've done this before and found it in cache */
  308. if (false !== $file = static::seen($className)) {
  309. if (!$this->exists($className))
  310. if (is_callable($file))
  311. $file = $this->loadLastResort($className, $file);
  312. elseif($file = stream_resolve_include_path($file))
  313. $file = static::loadFile($file);
  314. $this->alias($className, $currentClass);
  315. return $file;
  316. }
  317. /** We did not find it in cache, lets look for it shall we */
  318. /** replace \ with / and _ in CLASS NAME with / = PSR-0 in 3 lines */
  319. $file = preg_replace("/\\\|_(?=\w+$)/", DIRECTORY_SEPARATOR, $className);
  320. if (false === $file = stream_resolve_include_path("$file.php"))
  321. return false;
  322. /** have we loaded this file before could this be an alias */
  323. if (in_array($file, get_included_files())) {
  324. if (false !== $sameFile = array_search($file, static::$classMap))
  325. if (!$this->exists($className, $file))
  326. if (false !== strpos($sameFile, $className))
  327. $this->alias($sameFile, $className);
  328. return $file;
  329. }
  330. $state = array_merge(get_declared_classes(), get_declared_interfaces());
  331. if (false !== $result = static::loadFile($file)) {
  332. if ($this->exists($className, $file))
  333. $this->alias($className, $currentClass);
  334. elseif (false != $diff = array_diff(
  335. array_merge(get_declared_classes(), get_declared_interfaces()), $state))
  336. foreach ($diff as $autoLoaded)
  337. if ($this->exists($autoLoaded, $file))
  338. if (false !== strpos($autoLoaded, $className))
  339. $this->alias($autoLoaded, $className);
  340. if (!$this->exists($currentClass))
  341. $result = false;
  342. }
  343. return $result;
  344. }
  345. /**
  346. * Checks whether supplied string exists in a loaded class or interface.
  347. * As a convenience the supplied $mapping can be the value for seen.
  348. *
  349. * @param $className string The class or interface to verify
  350. * @param $mapping string (optional) value for map/seen if found to exist
  351. *
  352. * @return bool whether the class/interface exists without calling auto loader
  353. */
  354. private function exists($className, $mapping = null)
  355. {
  356. if (class_exists($className, false)
  357. || interface_exists($className, false))
  358. if (isset($mapping))
  359. return static::seen($className, $mapping);
  360. else
  361. return true;
  362. return false;
  363. }
  364. /**
  365. * Auto loader callback through __invoke object as function.
  366. *
  367. * @param $className string class/interface name to auto load
  368. *
  369. * @return mixed|null the reference from the include or null
  370. */
  371. public function __invoke($className)
  372. {
  373. if (empty($className))
  374. return false;
  375. if (false !== $includeReference = $this->discover($className))
  376. return $includeReference;
  377. static::thereCanBeOnlyOne();
  378. if (false !== $includeReference = $this->loadAliases($className))
  379. return $includeReference;
  380. if (false !== $includeReference = $this->loadPrefixes($className))
  381. return $includeReference;
  382. if (false !== $includeReference = $this->loadLastResort($className))
  383. return $includeReference;
  384. static::seen($className, true);
  385. return null;
  386. }
  387. }
  388. }
  389. namespace {
  390. /**
  391. * Include function in the root namespace to include files optimized
  392. * for the global context.
  393. *
  394. * @param $path string path of php file to include into the global context.
  395. *
  396. * @return mixed|bool false if the file could not be included.
  397. */
  398. function Luracast_Restler_autoloaderInclude($path) {
  399. return include $path;
  400. }
  401. }