Psr4ClassLoader.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. return null;
  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([$this, 'loadClass'], true, $prepend);
  75. }
  76. /**
  77. * Removes this instance from the registered autoloaders.
  78. */
  79. public function unregister()
  80. {
  81. spl_autoload_unregister([$this, 'loadClass']);
  82. }
  83. }