Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

88 rindas
2.3KB

  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. /**
  14. * Import namespace
  15. * ```
  16. * Import::using('yii\bootstrap\*');
  17. * Import::using('yii\widgets\ActiveForm');
  18. *
  19. * Import::using([
  20. * 'yii\helpers\Html',
  21. * 'yii\bootstrap\Html' => 'BHtml'
  22. * ]);
  23. * ```
  24. * @param string $namespace
  25. * @throws BadMethodCallException
  26. */
  27. public static function using($namespace, $as = null)
  28. {
  29. if (!static::$_registered) {
  30. spl_autoload_register(['Import', 'load']);
  31. static::$_registered = true;
  32. }
  33. if (is_array($namespace)) {
  34. foreach ($namespace as $class => $alias) {
  35. if (is_int($class)) {
  36. static::using($alias);
  37. } else {
  38. static::using($class, $alias);
  39. }
  40. }
  41. return;
  42. }
  43. $namespace = trim($namespace, '\\');
  44. if (($pos = strrpos($namespace, '\\')) !== false) {
  45. $ns = trim(substr($namespace, 0, $pos), '\\');
  46. $alias = substr($namespace, $pos + 1);
  47. } else {
  48. $ns = '';
  49. $alias = $namespace;
  50. }
  51. if ($alias === '*') {
  52. static::$_paths[$ns] = true;
  53. } else {
  54. static::$_classMap[$as ? : $alias] = $namespace;
  55. }
  56. }
  57. /**
  58. * Autoload class
  59. * @param string $class
  60. * @return boolean
  61. */
  62. public static function load($class)
  63. {
  64. if (empty(static::$_paths) && empty(static::$_classMap)) {
  65. return;
  66. }
  67. if (($pos = strrpos($class, '\\')) !== false) {
  68. $alias = substr($class, $pos + 1);
  69. } else {
  70. $alias = $class;
  71. }
  72. if (isset(static::$_classMap[$alias])) {
  73. return class_alias(static::$_classMap[$alias], $class);
  74. } else {
  75. foreach (array_keys(static::$_paths) as $path) {
  76. if (class_exists(rtrim($path . '\\' . $alias, '\\'))) {
  77. return class_alias(rtrim($path . '\\' . $alias, '\\'), $class);
  78. }
  79. }
  80. }
  81. }
  82. }