Psr4.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. * 从Map中获取文件
  188. */
  189. protected function searchMappedFile($class)
  190. {
  191. $prefix = $class;
  192. // work backwards through the namespace names of the fully-qualified
  193. // class name to find a mapped file name
  194. while (false !== $pos = strrpos($prefix, '\\')) {
  195. // retain the trailing namespace separator in the prefix
  196. $prefix = substr($class, 0, $pos + 1);
  197. // the rest is the relative class name
  198. $relativeClass = substr($class, $pos + 1);
  199. // try to load a mapped file for the prefix and relative class
  200. $mappedFile = $this->loadMappedFile($prefix, $relativeClass);
  201. if ($mappedFile) {
  202. return $mappedFile;
  203. }
  204. $prefix = rtrim($prefix, '\\');
  205. };
  206. //如果没有找到就在workspace中去找对应的文件 额外添加的方法
  207. $mappedFile = $this->loadMappedFile('workspace\\', $class);
  208. if ($mappedFile) {
  209. return $mappedFile;
  210. }
  211. return false;
  212. }
  213. /**
  214. * 通过类名加载文件
  215. * @param string $class 类名
  216. * @return string 文件路径
  217. */
  218. public function loadFileByClass($class)
  219. {
  220. // the current namespace prefix
  221. //replace "_" to "\" use common method to load class
  222. $class = str_replace("_", "\\", $class);
  223. if(!$this->searchMappedFile($class))
  224. {
  225. $notLoaded = isset(self::$lastErrorLoadedFile[$class]) ? self::$lastErrorLoadedFile[$class] : self::getClassName($class);
  226. throw new \Qii\Exceptions\FileNotFound(\Qii::i(1405, $notLoaded), __LINE__);
  227. }
  228. }
  229. /**
  230. * loadClass返回真正的类名
  231. *
  232. * @param string $class 类名
  233. */
  234. public function getClassName($class)
  235. {
  236. // the current namespace prefix
  237. //replace "_" to "\" use common method to load class
  238. $class = str_replace("_", "\\", $class);
  239. if($this->searchMappedFile($class))
  240. {
  241. return $class;
  242. }
  243. return str_replace('\\', '_', $class);
  244. }
  245. /**
  246. * Loads the class file for a given class name.
  247. *
  248. * @param string $class The fully-qualified class name.
  249. * @return mixed The mapped file name on success, or boolean false on
  250. * failure.
  251. */
  252. public function loadClass($class)
  253. {
  254. $args = func_get_args();
  255. //去掉第一个斜杠
  256. $class = array_shift($args);
  257. $class = preg_replace("/^\\\\/", "", $class);
  258. $class = $this->getClassName($class);
  259. array_unshift($args, $class);
  260. if (class_exists($class, false)) {
  261. return call_user_func_array(array($this, 'instance'), $args);
  262. }
  263. if ($this->loadFileByClass($class)) {
  264. return call_user_func_array(array($this, 'instance'), $args);
  265. }
  266. throw new \Qii\Exceptions\ClassNotFound(\Qii::i(1103, $class), __LINE__);
  267. }
  268. /**
  269. * 调用静态的方法
  270. * @param string $class 类名
  271. * @param string $method 方法名
  272. * @return mixed
  273. */
  274. public static function loadStatic($class, $method)
  275. {
  276. $args = func_get_args();
  277. $class = \Qii\Autoloader\Psr4::getInstance()->getClassName(array_shift($args));
  278. $method = array_shift($args);
  279. return call_user_func_array(array($class, $method), $args);
  280. }
  281. /**
  282. * 获取文件的绝对路径
  283. * @param string $path
  284. * @param bool $exists 是否使用realpath
  285. * @return string 真实路径
  286. */
  287. public static function realpath($path)
  288. {
  289. if (isset(self::$_realpath[$path])) return self::$_realpath[$path];
  290. $drive = '';
  291. if (OS === 'WIN') {
  292. $path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path);
  293. if (preg_match('/(phar\:\\\\|[a-zA-Z]\:)(.*)/', $path, $matches)) {
  294. list(, $drive, $path) = $matches;
  295. } else {
  296. $cwd = getcwd();
  297. $drive = substr($cwd, 0, 2);
  298. if (substr($path, 0, 1) != DIRECTORY_SEPARATOR) {
  299. $path = substr($cwd, 3) . DIRECTORY_SEPARATOR . $path;
  300. }
  301. }
  302. } elseif (substr($path, 0, 1) != DIRECTORY_SEPARATOR) {
  303. $path = getcwd() . DIRECTORY_SEPARATOR . $path;
  304. }
  305. $stack = array();
  306. $parts = explode(DIRECTORY_SEPARATOR, $path);
  307. foreach ($parts as $dir) {
  308. if (strlen($dir) && $dir !== '.') {
  309. if ($dir == '..') {
  310. array_pop($stack);
  311. } else {
  312. array_push($stack, $dir);
  313. }
  314. }
  315. }
  316. $realPath = str_replace(DIRECTORY_SEPARATOR, '/', $drive . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $stack));
  317. self::$_realpath[$path] = $realPath;
  318. return $realPath;
  319. }
  320. /**
  321. * Load the mapped file for a namespace prefix and relative class.
  322. *
  323. * @param string $prefix The namespace prefix.
  324. * @param string $relativeClass The relative class name.
  325. * @return mixed Boolean false if no mapped file can be loaded, or the
  326. * name of the mapped file that was loaded.
  327. */
  328. protected function loadMappedFile($prefix, $relativeClass)
  329. {
  330. if (isset(self::$cachedFiles[$prefix . '_' . $relativeClass])) return self::$cachedFiles[$prefix . '_' . $relativeClass];
  331. // are there any base directories for this namespace prefix?
  332. if (isset($this->prefixes[$prefix]) === false) {
  333. //if there any base directories , add self to prefix
  334. $this->addNamespace($prefix, $prefix);
  335. //return false;
  336. }
  337. $prefix = trim($prefix, '\\') . '\\';
  338. $file = '';
  339. // look through base directories for this namespace prefix
  340. foreach ($this->prefixes[$prefix] as $baseDir) {
  341. $file = str_replace("/", DS, $baseDir
  342. . str_replace('\\', DS, $relativeClass)
  343. . '.php');
  344. // if the mapped file exists, require it
  345. if ($this->requireFile($file)) {
  346. self::$cachedFiles[$prefix . '_' . $relativeClass] = $file;
  347. return $file;
  348. }
  349. }
  350. self::$lastErrorLoadedFile[$relativeClass] = $file;
  351. // never found it
  352. return false;
  353. }
  354. /**
  355. * If a file exists, require it from the file system.
  356. *
  357. * @param string $file The file to require.
  358. * @return bool True if the file exists, false if not.
  359. */
  360. protected function requireFile($file)
  361. {
  362. return \Qii\Autoloader\Import::requires($file);
  363. }
  364. /**
  365. * instance class
  366. * @param string $class
  367. * @return object
  368. */
  369. public function instance()
  370. {
  371. $args = func_get_args();
  372. $class = array_shift($args);
  373. $className = $this->getClassName($class);
  374. if (isset(self::$_loadedClass[$className])) return self::$_loadedClass[$className];
  375. if (!class_exists($className, false)) {
  376. throw new \Qii\Exceptions\CallUndefinedClass(\Qii::i('1105', $className), __LINE__);
  377. }
  378. $refClass = new \ReflectionClass($className);
  379. self::$_loadedClass[$className] = $instance = $refClass->newInstanceArgs($args);
  380. //如果有_initialize方法就自动调用_initialize方法,并将参数传递给_initialize方法
  381. if ($refClass->hasMethod('_initialize')) {
  382. call_user_func_array(array($instance, '_initialize'), $args);
  383. }
  384. return $instance;
  385. }
  386. }