Psr4ClassLoader.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. @trigger_error('The '.__NAMESPACE__.'\Psr4ClassLoader class is deprecated since Symfony 3.3 and will be removed in 4.0. Use Composer instead.', E_USER_DEPRECATED);
  12. /**
  13. * A PSR-4 compatible class loader.
  14. *
  15. * See http://www.php-fig.org/psr/psr-4/
  16. *
  17. * @author Alexander M. Turek <me@derrabus.de>
  18. *
  19. * @deprecated since version 3.3, to be removed in 4.0.
  20. */
  21. class Psr4ClassLoader
  22. {
  23. private $prefixes = [];
  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[] = [$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 list($currentPrefix, $currentBaseDir)) {
  43. if (0 === strpos($class, $currentPrefix)) {
  44. $classWithoutPrefix = substr($class, \strlen($currentPrefix));
  45. $file = $currentBaseDir.str_replace('\\', \DIRECTORY_SEPARATOR, $classWithoutPrefix).'.php';
  46. if (file_exists($file)) {
  47. return $file;
  48. }
  49. }
  50. }
  51. }
  52. /**
  53. * @param string $class
  54. *
  55. * @return bool
  56. */
  57. public function loadClass($class)
  58. {
  59. $file = $this->findFile($class);
  60. if (null !== $file) {
  61. require $file;
  62. return true;
  63. }
  64. return false;
  65. }
  66. /**
  67. * Registers this instance as an autoloader.
  68. *
  69. * @param bool $prepend
  70. */
  71. public function register($prepend = false)
  72. {
  73. spl_autoload_register([$this, 'loadClass'], true, $prepend);
  74. }
  75. /**
  76. * Removes this instance from the registered autoloaders.
  77. */
  78. public function unregister()
  79. {
  80. spl_autoload_unregister([$this, 'loadClass']);
  81. }
  82. }