Drupal investigation

Psr4ClassLoader.php 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ClassLoader;
  11. /**
  12. * A PSR-4 compatible class loader.
  13. *
  14. * See http://www.php-fig.org/psr/psr-4/
  15. *
  16. * @author Alexander M. Turek <me@derrabus.de>
  17. */
  18. class Psr4ClassLoader
  19. {
  20. /**
  21. * @var array
  22. */
  23. private $prefixes = array();
  24. /**
  25. * @param string $prefix
  26. * @param string $baseDir
  27. */
  28. public function addPrefix($prefix, $baseDir)
  29. {
  30. $prefix = trim($prefix, '\\').'\\';
  31. $baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
  32. $this->prefixes[] = array($prefix, $baseDir);
  33. }
  34. /**
  35. * @param string $class
  36. *
  37. * @return string|null
  38. */
  39. public function findFile($class)
  40. {
  41. $class = ltrim($class, '\\');
  42. foreach ($this->prefixes as $current) {
  43. list($currentPrefix, $currentBaseDir) = $current;
  44. if (0 === strpos($class, $currentPrefix)) {
  45. $classWithoutPrefix = substr($class, strlen($currentPrefix));
  46. $file = $currentBaseDir.str_replace('\\', DIRECTORY_SEPARATOR, $classWithoutPrefix).'.php';
  47. if (file_exists($file)) {
  48. return $file;
  49. }
  50. }
  51. }
  52. }
  53. /**
  54. * @param string $class
  55. *
  56. * @return bool
  57. */
  58. public function loadClass($class)
  59. {
  60. $file = $this->findFile($class);
  61. if (null !== $file) {
  62. require $file;
  63. return true;
  64. }
  65. return false;
  66. }
  67. /**
  68. * Registers this instance as an autoloader.
  69. *
  70. * @param bool $prepend
  71. */
  72. public function register($prepend = false)
  73. {
  74. spl_autoload_register(array($this, 'loadClass'), true, $prepend);
  75. }
  76. /**
  77. * Removes this instance from the registered autoloaders.
  78. */
  79. public function unregister()
  80. {
  81. spl_autoload_unregister(array($this, 'loadClass'));
  82. }
  83. }