Psr4.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. namespace Qii\Autoloader;
  3. /**
  4. * Psr4 规范
  5. *
  6. */
  7. class Psr4
  8. {
  9. /**
  10. * 将查找过的文件放入缓存
  11. */
  12. protected static $cachedFiles = array();
  13. /**
  14. * 是否使用namespace
  15. */
  16. protected $useNamespace = array();
  17. /**
  18. * 添加namespace前缀对应的目录,只要是以这个前缀开头的文件都在指定目录中去查找
  19. * 前缀可以对应多个目录,找的时候会去遍历数组
  20. * @var array
  21. */
  22. protected $prefixes = array();
  23. /**
  24. * 当前class的初始化
  25. */
  26. private static $_instance = null;
  27. /**
  28. * @var APP_LOAD_PREFIX 保存类到以APP_LOAD_PREFIX开头的key中
  29. */
  30. const APP_LOAD_PREFIX = '__qii_psr4_instance';
  31. /**
  32. * @var $_loadedClass 保存加载过的类
  33. */
  34. protected static $_loadedClass = array();
  35. /**
  36. * @var $_realpath 将转换后的路径存放到此变量中
  37. */
  38. protected static $_realpath = array();
  39. /**
  40. * 最后一次没有加载到文件的错误路径
  41. * @var array $lastErrorLoadedFile
  42. */
  43. protected static $lastErrorLoadedFile = array();
  44. /**
  45. * 注册自动加载类
  46. *
  47. */
  48. private function __construct()
  49. {
  50. }
  51. /**
  52. * 单例模式
  53. */
  54. public static function getInstance()
  55. {
  56. if (self::$_instance == null) {
  57. self::$_instance = new self();
  58. }
  59. return self::$_instance;
  60. }
  61. /**
  62. * 注册自动加载类
  63. *
  64. * @return void
  65. */
  66. public function register()
  67. {
  68. spl_autoload_register(array($this, 'loadFileByClass'));
  69. return $this;
  70. }
  71. /**
  72. * Setting is use namespace for class
  73. *
  74. * @param $prefix 以prefix前缀开头的使用namespace
  75. * @param bool $useNamespace
  76. * @return object $this
  77. */
  78. public function setUseNamespace($prefix, $useNamespace = true)
  79. {
  80. $this->useNamespace[$prefix] = $useNamespace;
  81. return $this;
  82. }
  83. /**
  84. * Adds a base directory for a namespace prefix.
  85. *
  86. * @param string $prefix The namespace prefix.
  87. * @param string $baseDir A base directory for class files in the
  88. * namespace.
  89. * @param bool $prepend If true, prepend the base directory to the stack
  90. * instead of appending it; this causes it to be searched first rather
  91. * than last.
  92. * @return void
  93. */
  94. public function addNamespace($prefix, $baseDir, $prepend = false)
  95. {
  96. // normalize namespace prefix
  97. $prefix = trim($prefix, '\\') . '\\';
  98. // normalize the base directory with a trailing separator
  99. $baseDir = rtrim($baseDir, '/') . DIRECTORY_SEPARATOR;
  100. $baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . '/';
  101. // initialize the namespace prefix array
  102. if (isset($this->prefixes[$prefix]) === false) {
  103. $this->prefixes[$prefix] = array();
  104. }
  105. if (in_array($baseDir, $this->prefixes[$prefix])) {
  106. return $this;
  107. }
  108. // retain the base directory for the namespace prefix
  109. if ($prepend) {
  110. array_unshift($this->prefixes[$prefix], $baseDir);
  111. } else {
  112. array_push($this->prefixes[$prefix], $baseDir);
  113. }
  114. return $this;
  115. }
  116. /**
  117. * 移除某一个namespace下的指定路径
  118. * @param string $prefix 前缀
  119. * @param string $baseDir 路径
  120. * @return array
  121. */
  122. public function removeNameSpace($prefix, $baseDir)
  123. {
  124. // normalize namespace prefix
  125. $prefix = trim($prefix, '\\') . '\\';
  126. // normalize the base directory with a trailing separator
  127. $baseDir = rtrim($baseDir, '/') . DIRECTORY_SEPARATOR;
  128. $baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . '/';
  129. // initialize the namespace prefix array
  130. if (isset($this->prefixes[$prefix]) === false) {
  131. return false;
  132. }
  133. foreach ($this->prefixes[$prefix] AS $key => $dir) {
  134. if ($dir == $baseDir) unset($this->prefixes[$prefix][$key]);
  135. }
  136. return $this->prefixes;
  137. }
  138. /**
  139. * 返回namespace路径
  140. */
  141. public function getNamespace($prefix)
  142. {
  143. // normalize namespace prefix
  144. $prefix = trim($prefix, '\\') . '\\';
  145. if (isset($this->prefixes[$prefix])) return $this->prefixes[$prefix];
  146. return '';
  147. }
  148. /**
  149. * 通过文件名返回路径
  150. * @param string $fileName 文件名
  151. * @return string
  152. */
  153. public function getFileByPrefix($fileName)
  154. {
  155. $fileName = str_replace(array('/', '\\'), DS, $fileName);
  156. $prefixes = explode(DS, $fileName, 2);
  157. $dirs = isset($this->prefixes['workspace\\']) ? $this->prefixes['workspace\\'] : array();
  158. if (count($prefixes) == 2) {
  159. if (isset($this->prefixes[$prefixes[0]])) $dirs = $this->prefixes[$prefixes[0]];
  160. }
  161. foreach ($dirs as $baseDir) {
  162. if (is_file($baseDir . DS . $fileName)) {
  163. return $baseDir . DS . $fileName;
  164. }
  165. }
  166. return $fileName;
  167. }
  168. /**
  169. * 获取指定文件夹路径
  170. * @param string $folder 路径
  171. * @return string 路径
  172. */
  173. public function getFolderByPrefix($folder)
  174. {
  175. $fileName = str_replace(array('/', '\\'), DS, $folder);
  176. $prefixes = explode(DS, $fileName, 2);
  177. $dirs = isset($this->prefixes['workspace\\']) ? $this->prefixes['workspace\\'] : array();
  178. if (count($prefixes) == 2) {
  179. if (isset($this->prefixes[$prefixes[0]])) $dirs = $this->prefixes[$prefixes[0]];
  180. }
  181. foreach ($dirs as $baseDir) {
  182. return $baseDir . DS . $folder;
  183. }
  184. return $folder;
  185. }
  186. /**
  187. * 通过类名加载文件
  188. * @param string $class 类名
  189. * @return string 文件路径
  190. */
  191. public function loadFileByClass($class)
  192. {
  193. // the current namespace prefix
  194. //replace "_" to "\" use common method to load class
  195. $class = str_replace("_", "\\", $class);
  196. $prefix = $class;
  197. // work backwards through the namespace names of the fully-qualified
  198. // class name to find a mapped file name
  199. while (false !== $pos = strrpos($prefix, '\\')) {
  200. // retain the trailing namespace separator in the prefix
  201. $prefix = substr($class, 0, $pos + 1);
  202. // the rest is the relative class name
  203. $relativeClass = substr($class, $pos + 1);
  204. // try to load a mapped file for the prefix and relative class
  205. $mappedFile = $this->loadMappedFile($prefix, $relativeClass);
  206. if ($mappedFile) {
  207. return $mappedFile;
  208. }
  209. // remove the trailing namespace separator for the next iteration
  210. // of strrpos()
  211. $prefix = rtrim($prefix, '\\');
  212. };
  213. //如果没有找到就在workspace中去找对应的文件 额外添加的方法
  214. $mappedFile = $this->loadMappedFile('workspace\\', $class);
  215. if ($mappedFile) {
  216. return $mappedFile;
  217. }
  218. $notLoaded = isset(self::$lastErrorLoadedFile[$class]) ? self::$lastErrorLoadedFile[$class] : self::getClassName($class);
  219. throw new \Qii\Exceptions\FileNotFound(\Qii::i(1405, $notLoaded), __LINE__);
  220. }
  221. /**
  222. * loadClass返回真正的类名
  223. *
  224. * @param string $class 类名
  225. */
  226. public function getClassName($class)
  227. {
  228. // the current namespace prefix
  229. //replace "_" to "\" use common method to load class
  230. $class = str_replace("_", "\\", $class);
  231. $prefix = $class;
  232. // work backwards through the namespace names of the fully-qualified
  233. // class name to find a mapped file name
  234. while (false !== $pos = strrpos($prefix, '\\')) {
  235. // retain the trailing namespace separator in the prefix
  236. $prefix = substr($class, 0, $pos + 1);
  237. // the rest is the relative class name
  238. $relativeClass = substr($class, $pos + 1);
  239. // try to load a mapped file for the prefix and relative class
  240. $mappedFile = $this->loadMappedFile($prefix, $relativeClass);
  241. if ($mappedFile) {
  242. return $class;
  243. }
  244. // remove the trailing namespace separator for the next iteration
  245. // of strrpos()
  246. $prefix = rtrim($prefix, '\\');
  247. };
  248. //如果没有找到就在workspace中去找对应的文件 额外添加的方法
  249. $mappedFile = $this->loadMappedFile('workspace\\', $class);
  250. if ($mappedFile)
  251. {
  252. return $class;
  253. }
  254. return str_replace('\\', '_', $class);
  255. }
  256. /**
  257. * Loads the class file for a given class name.
  258. *
  259. * @param string $class The fully-qualified class name.
  260. * @return mixed The mapped file name on success, or boolean false on
  261. * failure.
  262. */
  263. public function loadClass($class)
  264. {
  265. $args = func_get_args();
  266. //去掉第一个斜杠
  267. $class = array_shift($args);
  268. $class = preg_replace("/^\\\\/", "", $class);
  269. $class = $this->getClassName($class);
  270. array_unshift($args, $class);
  271. if (class_exists($class, false)) {
  272. return call_user_func_array(array($this, 'instance'), $args);
  273. }
  274. if ($this->loadFileByClass($class)) {
  275. return call_user_func_array(array($this, 'instance'), $args);
  276. }
  277. throw new \Qii\Exceptions\ClassNotFound(\Qii::i(1103, $class), __LINE__);
  278. }
  279. /**
  280. * 调用静态的方法
  281. * @param string $class 类名
  282. * @param string $method 方法名
  283. * @return mixed
  284. */
  285. public static function loadStatic($class, $method)
  286. {
  287. $args = func_get_args();
  288. $class = \Qii\Autoloader\Psr4::getInstance()->getClassName(array_shift($args));
  289. $method = array_shift($args);
  290. return call_user_func_array(array($class, $method), $args);
  291. }
  292. /**
  293. * 获取文件的绝对路径
  294. * @param string $path
  295. * @param bool $exists 是否使用realpath
  296. * @return string 真实路径
  297. */
  298. public static function realpath($path)
  299. {
  300. if (isset(self::$_realpath[$path])) return self::$_realpath[$path];
  301. $drive = '';
  302. if (OS === 'WIN') {
  303. $path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path);
  304. if (preg_match('/(phar\:\\\\|[a-zA-Z]\:)(.*)/', $path, $matches)) {
  305. list(, $drive, $path) = $matches;
  306. } else {
  307. $cwd = getcwd();
  308. $drive = substr($cwd, 0, 2);
  309. if (substr($path, 0, 1) != DIRECTORY_SEPARATOR) {
  310. $path = substr($cwd, 3) . DIRECTORY_SEPARATOR . $path;
  311. }
  312. }
  313. } elseif (substr($path, 0, 1) != DIRECTORY_SEPARATOR) {
  314. $path = getcwd() . DIRECTORY_SEPARATOR . $path;
  315. }
  316. $stack = array();
  317. $parts = explode(DIRECTORY_SEPARATOR, $path);
  318. foreach ($parts as $dir) {
  319. if (strlen($dir) && $dir !== '.') {
  320. if ($dir == '..') {
  321. array_pop($stack);
  322. } else {
  323. array_push($stack, $dir);
  324. }
  325. }
  326. }
  327. $realPath = str_replace(DIRECTORY_SEPARATOR, '/', $drive . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $stack));
  328. self::$_realpath[$path] = $realPath;
  329. return $realPath;
  330. }
  331. /**
  332. * Load the mapped file for a namespace prefix and relative class.
  333. *
  334. * @param string $prefix The namespace prefix.
  335. * @param string $relativeClass The relative class name.
  336. * @return mixed Boolean false if no mapped file can be loaded, or the
  337. * name of the mapped file that was loaded.
  338. */
  339. protected function loadMappedFile($prefix, $relativeClass)
  340. {
  341. if (isset(self::$cachedFiles[$prefix . '_' . $relativeClass])) return self::$cachedFiles[$prefix . '_' . $relativeClass];
  342. // are there any base directories for this namespace prefix?
  343. if (isset($this->prefixes[$prefix]) === false) {
  344. //if there any base directories , add self to prefix
  345. $this->addNamespace($prefix, $prefix);
  346. //return false;
  347. }
  348. $prefix = trim($prefix, '\\') . '\\';
  349. $file = '';
  350. // look through base directories for this namespace prefix
  351. foreach ($this->prefixes[$prefix] as $baseDir) {
  352. $file = str_replace("/", DS, $baseDir
  353. . str_replace('\\', DS, $relativeClass)
  354. . '.php');
  355. // if the mapped file exists, require it
  356. if ($this->requireFile($file)) {
  357. self::$cachedFiles[$prefix . '_' . $relativeClass] = $file;
  358. return $file;
  359. }
  360. }
  361. self::$lastErrorLoadedFile[$relativeClass] = $file;
  362. // never found it
  363. return false;
  364. }
  365. /**
  366. * If a file exists, require it from the file system.
  367. *
  368. * @param string $file The file to require.
  369. * @return bool True if the file exists, false if not.
  370. */
  371. protected function requireFile($file)
  372. {
  373. return \Qii\Autoloader\Import::requires($file);
  374. }
  375. /**
  376. * instance class
  377. * @param string $class
  378. * @return object
  379. */
  380. public function instance()
  381. {
  382. $args = func_get_args();
  383. $class = array_shift($args);
  384. $className = $this->getClassName($class);
  385. if (isset(self::$_loadedClass[$className])) return self::$_loadedClass[$className];
  386. if (!class_exists($className, false)) {
  387. throw new \Qii\Exceptions\CallUndefinedClass(\Qii::i('1105', $className), __LINE__);
  388. }
  389. $loader = new \ReflectionClass($className);
  390. //try {
  391. self::$_loadedClass[$className] = $instance = $loader->newInstanceArgs($args);
  392. //如果有_initialize方法就自动调用_initialize方法,并将参数传递给_initialize方法
  393. if ($loader->hasMethod('_initialize')) {
  394. call_user_func_array(array($instance, '_initialize'), $args);
  395. }
  396. return $instance;
  397. /*} catch (Exception $e) {
  398. throw new \Exception($e->getMessage(), __LINE__);
  399. }*/
  400. }
  401. }