Autoloader.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. /**
  3. * Autoloader
  4. *
  5. * This file is part of Grav MediaEmbed plugin.
  6. *
  7. * Dual licensed under the MIT or GPL Version 3 licenses, see LICENSE.
  8. * http://benjamin-regler.de/license/
  9. */
  10. namespace Grav\Plugin\MediaEmbed;
  11. /**
  12. * Autoloader
  13. */
  14. class Autoloader
  15. {
  16. protected $routes = [];
  17. public function __construct($routes = [])
  18. {
  19. // Set routes for autoloading
  20. if (!is_array($routes) || count($routes) == 0) {
  21. $routes = [__NAMESPACE__ => __DIR__];
  22. }
  23. $this->route($routes);
  24. }
  25. public function route($var = null, $reset = true)
  26. {
  27. if ($var !== null && is_array($var)) {
  28. if ($reset) {
  29. $this->routes = [];
  30. }
  31. // Setup routes
  32. foreach ($var as $prefix => $path) {
  33. if (false !== strrpos($prefix, '\\')) {
  34. // Prefix is a namespaced path
  35. $prefix = rtrim($prefix, '_\\') . '\\';
  36. } else {
  37. // Prefix contain underscores
  38. $prefix = rtrim($prefix, '_') . '_';
  39. }
  40. $this->routes[$prefix] = rtrim($path, '/\\') . '/';
  41. }
  42. }
  43. return $this->routes;
  44. }
  45. /**
  46. * Autoload classes
  47. *
  48. * @param string $class Class name
  49. *
  50. * @return mixed false FALSE if unable to load $class; Class name if
  51. * $class is successfully loaded
  52. */
  53. public function autoload($class)
  54. {
  55. foreach ($this->routes as $prefix => $path) {
  56. // Only load classes of MediaEmbed plugin
  57. if (false !== strpos($class, $prefix)) {
  58. // Remove prefix from class
  59. $class = substr($class, strlen($prefix));
  60. // Replace namespace tokens to directory separators
  61. $file = $path . preg_replace('#\\\|_(?!.+\\\)#', '/', $class) . '.php';
  62. // Load class
  63. if (stream_resolve_include_path($file)) {
  64. return include_once($file);
  65. }
  66. return false;
  67. }
  68. }
  69. return false;
  70. }
  71. /**
  72. * Registers this instance as an autoloader
  73. *
  74. * @param bool $prepend Whether to prepend the autoloader or not
  75. */
  76. public function register($prepend = false)
  77. {
  78. spl_autoload_register(array($this, 'autoload'), false, $prepend);
  79. }
  80. /**
  81. * Unregisters this instance as an autoloader
  82. */
  83. public function unregister()
  84. {
  85. spl_autoload_unregister(array($this, 'autoload'));
  86. }
  87. }