99 行
2.7KB

  1. <?php
  2. /**
  3. * Import. Use to import all class under namespace
  4. *
  5. * @author Misbahul D Munir <misbahuldmunir@gmail.com>
  6. * @since 1.0
  7. */
  8. class Import
  9. {
  10. private static $_paths = [];
  11. private static $_classMap = [];
  12. private static $_registered = false;
  13. private static $test_class_not_found = [] ;
  14. /**
  15. * Import namespace
  16. * ```
  17. * Import::using('yii\bootstrap\*');
  18. * Import::using('yii\widgets\ActiveForm');
  19. *
  20. * Import::using([
  21. * 'yii\helpers\Html',
  22. * 'yii\bootstrap\Html' => 'BHtml'
  23. * ]);
  24. * ```
  25. * @param string $namespace
  26. * @throws BadMethodCallException
  27. */
  28. public static function using($namespace, $as = null)
  29. {
  30. if (!static::$_registered) {
  31. spl_autoload_register(['Import', 'load']);
  32. static::$_registered = true;
  33. }
  34. if (is_array($namespace)) {
  35. foreach ($namespace as $class => $alias) {
  36. if (is_int($class)) {
  37. static::using($alias);
  38. } else {
  39. static::using($class, $alias);
  40. }
  41. }
  42. return;
  43. }
  44. $namespace = trim($namespace, '\\');
  45. if (($pos = strrpos($namespace, '\\')) !== false) {
  46. $ns = trim(substr($namespace, 0, $pos), '\\');
  47. $alias = substr($namespace, $pos + 1);
  48. } else {
  49. $ns = '';
  50. $alias = $namespace;
  51. }
  52. if ($alias === '*') {
  53. static::$_paths[$ns] = true;
  54. } else {
  55. static::$_classMap[$as ? : $alias] = $namespace;
  56. }
  57. }
  58. /**
  59. * Autoload class
  60. * @param string $class
  61. * @return boolean
  62. */
  63. public static function load($class)
  64. {
  65. if(!isset(static::$test_class_not_found[$class]))
  66. static::$test_class_not_found[$class] = 0 ;
  67. static::$test_class_not_found[$class] ++ ;
  68. if(static::$test_class_not_found[$class] > 30) {
  69. throw new \yii\base\ErrorException('Class not found : '.$class) ;
  70. }
  71. if (empty(static::$_paths) && empty(static::$_classMap)) {
  72. return;
  73. }
  74. if (($pos = strrpos($class, '\\')) !== false) {
  75. $alias = substr($class, $pos + 1);
  76. } else {
  77. $alias = $class;
  78. }
  79. if (isset(static::$_classMap[$alias])) {
  80. return class_alias(static::$_classMap[$alias], $class);
  81. } else {
  82. foreach (array_keys(static::$_paths) as $path) {
  83. if (class_exists(rtrim($path . '\\' . $alias, '\\'))) {
  84. return class_alias(rtrim($path . '\\' . $alias, '\\'), $class);
  85. }
  86. }
  87. }
  88. }
  89. }