Psr4ClassLoader.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. private $prefixes = array();
  21. /**
  22. * @param string $prefix
  23. * @param string $baseDir
  24. */
  25. public function addPrefix($prefix, $baseDir)
  26. {
  27. $prefix = trim($prefix, '\\').'\\';
  28. $baseDir = rtrim($baseDir, \DIRECTORY_SEPARATOR).\DIRECTORY_SEPARATOR;
  29. $this->prefixes[] = array($prefix, $baseDir);
  30. }
  31. /**
  32. * @param string $class
  33. *
  34. * @return string|null
  35. */
  36. public function findFile($class)
  37. {
  38. $class = ltrim($class, '\\');
  39. foreach ($this->prefixes as $current) {
  40. list($currentPrefix, $currentBaseDir) = $current;
  41. if (0 === strpos($class, $currentPrefix)) {
  42. $classWithoutPrefix = substr($class, \strlen($currentPrefix));
  43. $file = $currentBaseDir.str_replace('\\', \DIRECTORY_SEPARATOR, $classWithoutPrefix).'.php';
  44. if (file_exists($file)) {
  45. return $file;
  46. }
  47. }
  48. }
  49. }
  50. /**
  51. * @param string $class
  52. *
  53. * @return bool
  54. */
  55. public function loadClass($class)
  56. {
  57. $file = $this->findFile($class);
  58. if (null !== $file) {
  59. require $file;
  60. return true;
  61. }
  62. return false;
  63. }
  64. /**
  65. * Registers this instance as an autoloader.
  66. *
  67. * @param bool $prepend
  68. */
  69. public function register($prepend = false)
  70. {
  71. spl_autoload_register(array($this, 'loadClass'), true, $prepend);
  72. }
  73. /**
  74. * Removes this instance from the registered autoloaders.
  75. */
  76. public function unregister()
  77. {
  78. spl_autoload_unregister(array($this, 'loadClass'));
  79. }
  80. }