Psr.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. //如果是不使用namespace,就将namespace转换成下划线的形式
  229. $useNamespace = false;
  230. //将_隔开的统一替换成namespace方式,如果不使用namespace就再替换回来
  231. $class = str_replace('_', '\\', $class);
  232. if (stristr($class, '\\')) {
  233. $prefix = explode('\\', ltrim($class, '\\'))[0];
  234. $useNamespace = isset($this->useNamespace[$prefix]) && $this->useNamespace[$prefix] ? true : false;
  235. }
  236. if (!$useNamespace) {
  237. $class = str_replace('\\', '_', $class);
  238. }
  239. return $class;
  240. }
  241. /**
  242. * Loads the class file for a given class name.
  243. *
  244. * @param string $class The fully-qualified class name.
  245. * @return mixed The mapped file name on success, or boolean false on
  246. * failure.
  247. */
  248. public function loadClass($class)
  249. {
  250. $args = func_get_args();
  251. //去掉第一个斜杠
  252. $class = array_shift($args);
  253. $class = preg_replace("/^\\\\/", "", $class);
  254. $class = $this->getClassName($class);
  255. array_unshift($args, $class);
  256. if (class_exists($class, false)) {
  257. return call_user_func_array(array($this, 'instance'), $args);
  258. }
  259. if ($this->loadFileByClass($class)) {
  260. return call_user_func_array(array($this, 'instance'), $args);
  261. }
  262. throw new \Qii\Exceptions\ClassNotFound(\Qii::i(1103, $class), __LINE__);
  263. }
  264. /**
  265. * 调用静态的方法
  266. * @param string $class 类名
  267. * @param string $method 方法名
  268. * @return mixed
  269. */
  270. public static function loadStatic($class, $method)
  271. {
  272. $args = func_get_args();
  273. $class = \Qii\Autoloader\Psr4::getInstance()->getClassName(array_shift($args));
  274. $method = array_shift($args);
  275. return call_user_func_array(array($class, $method), $args);
  276. }
  277. /**
  278. * 获取文件的绝对路径
  279. * @param string $path
  280. * @param bool $exists 是否使用realpath
  281. * @return string 真实路径
  282. */
  283. public static function realpath($path)
  284. {
  285. if (isset(self::$_realpath[$path])) return self::$_realpath[$path];
  286. $drive = '';
  287. if (OS === 'WIN') {
  288. $path = preg_replace('/[\\\\\/]/', DIRECTORY_SEPARATOR, $path);
  289. if (preg_match('/(phar\:\\\\|[a-zA-Z]\:)(.*)/', $path, $matches)) {
  290. list(, $drive, $path) = $matches;
  291. } else {
  292. $cwd = getcwd();
  293. $drive = substr($cwd, 0, 2);
  294. if (substr($path, 0, 1) != DIRECTORY_SEPARATOR) {
  295. $path = substr($cwd, 3) . DIRECTORY_SEPARATOR . $path;
  296. }
  297. }
  298. } elseif (substr($path, 0, 1) != DIRECTORY_SEPARATOR) {
  299. $path = getcwd() . DIRECTORY_SEPARATOR . $path;
  300. }
  301. $stack = array();
  302. $parts = explode(DIRECTORY_SEPARATOR, $path);
  303. foreach ($parts as $dir) {
  304. if (strlen($dir) && $dir !== '.') {
  305. if ($dir == '..') {
  306. array_pop($stack);
  307. } else {
  308. array_push($stack, $dir);
  309. }
  310. }
  311. }
  312. $realPath = str_replace(DIRECTORY_SEPARATOR, '/', $drive . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $stack));
  313. self::$_realpath[$path] = $realPath;
  314. return $realPath;
  315. }
  316. /**
  317. * Load the mapped file for a namespace prefix and relative class.
  318. *
  319. * @param string $prefix The namespace prefix.
  320. * @param string $relativeClass The relative class name.
  321. * @return mixed Boolean false if no mapped file can be loaded, or the
  322. * name of the mapped file that was loaded.
  323. */
  324. protected function loadMappedFile($prefix, $relativeClass)
  325. {
  326. if (isset(self::$cachedFiles[$prefix . '_' . $relativeClass])) return self::$cachedFiles[$prefix . '_' . $relativeClass];
  327. // are there any base directories for this namespace prefix?
  328. if (isset($this->prefixes[$prefix]) === false) {
  329. //if there any base directories , add self to prefix
  330. $this->addNamespace($prefix, $prefix);
  331. //return false;
  332. }
  333. $prefix = trim($prefix, '\\') . '\\';
  334. $file = '';
  335. // look through base directories for this namespace prefix
  336. foreach ($this->prefixes[$prefix] as $baseDir) {
  337. $file = str_replace("/", DS, $baseDir
  338. . str_replace('\\', DS, $relativeClass)
  339. . '.php');
  340. // if the mapped file exists, require it
  341. if ($this->requireFile($file)) {
  342. self::$cachedFiles[$prefix . '_' . $relativeClass] = $file;
  343. return $file;
  344. }
  345. }
  346. self::$lastErrorLoadedFile[$relativeClass] = $file;
  347. // never found it
  348. return false;
  349. }
  350. /**
  351. * If a file exists, require it from the file system.
  352. *
  353. * @param string $file The file to require.
  354. * @return bool True if the file exists, false if not.
  355. */
  356. protected function requireFile($file)
  357. {
  358. return \Qii\Autoloader\Import::requires($file);
  359. }
  360. /**
  361. * instance class
  362. * @param string $class
  363. * @return object
  364. */
  365. public function instance()
  366. {
  367. $args = func_get_args();
  368. $class = array_shift($args);
  369. $className = $this->getClassName($class);
  370. if (isset(self::$_loadedClass[$className])) return self::$_loadedClass[$className];
  371. if (!class_exists($className, false)) {
  372. throw new \Qii\Exceptions\CallUndefinedClass(\Qii\Application::i('1105', $className), __LINE__);
  373. }
  374. $loader = new \ReflectionClass($className);
  375. //try {
  376. self::$_loadedClass[$className] = $instance = $loader->newInstanceArgs($args);
  377. //如果有_initialize方法就自动调用_initialize方法,并将参数传递给_initialize方法
  378. if ($loader->hasMethod('_initialize')) {
  379. call_user_func_array(array($instance, '_initialize'), $args);
  380. }
  381. return $instance;
  382. /*} catch (Exception $e) {
  383. throw new \Exception($e->getMessage(), __LINE__);
  384. }*/
  385. }
  386. }