Psr0FindFile.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Doctrine\Common\Reflection;
  3. use const DIRECTORY_SEPARATOR;
  4. use function is_file;
  5. use function str_replace;
  6. use function strpos;
  7. use function strrpos;
  8. use function substr;
  9. /**
  10. * Finds a class in a PSR-0 structure.
  11. */
  12. class Psr0FindFile implements ClassFinderInterface
  13. {
  14. /**
  15. * The PSR-0 prefixes.
  16. *
  17. * @var string[][]
  18. */
  19. protected $prefixes;
  20. /**
  21. * @param string[][] $prefixes An array of prefixes. Each key is a PHP namespace and each value is
  22. * a list of directories.
  23. */
  24. public function __construct($prefixes)
  25. {
  26. $this->prefixes = $prefixes;
  27. }
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function findFile($class)
  32. {
  33. if ($class[0] === '\\') {
  34. $class = substr($class, 1);
  35. }
  36. $lastNsPos = strrpos($class, '\\');
  37. if ($lastNsPos !== false) {
  38. // namespaced class name
  39. $classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $lastNsPos)) . DIRECTORY_SEPARATOR;
  40. $className = substr($class, $lastNsPos + 1);
  41. } else {
  42. // PEAR-like class name
  43. $classPath = null;
  44. $className = $class;
  45. }
  46. $classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
  47. foreach ($this->prefixes as $prefix => $dirs) {
  48. if (strpos($class, $prefix) !== 0) {
  49. continue;
  50. }
  51. foreach ($dirs as $dir) {
  52. if (is_file($dir . DIRECTORY_SEPARATOR . $classPath)) {
  53. return $dir . DIRECTORY_SEPARATOR . $classPath;
  54. }
  55. }
  56. }
  57. return null;
  58. }
  59. }