Project.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\CodeParser;
  12. use Hyperf\Stringable\Str;
  13. use Hyperf\Support\Composer;
  14. use RuntimeException;
  15. use function Hyperf\Collection\data_get;
  16. /**
  17. * Read composer.json autoload psr-4 rules to figure out the namespace or path.
  18. */
  19. class Project
  20. {
  21. public function namespace(string $path): string
  22. {
  23. $ext = pathinfo($path, PATHINFO_EXTENSION);
  24. if ($ext !== '') {
  25. $path = substr($path, 0, -(strlen($ext) + 1));
  26. } else {
  27. $path = trim($path, '/') . '/';
  28. }
  29. foreach ($this->getAutoloadRules() as $prefix => $prefixPath) {
  30. if ($this->isRootNamespace($prefix) || str_starts_with($path, $prefixPath)) {
  31. return $prefix . str_replace('/', '\\', substr($path, strlen($prefixPath)));
  32. }
  33. }
  34. throw new RuntimeException("Invalid project path: {$path}");
  35. }
  36. public function className(string $path): string
  37. {
  38. return $this->namespace($path);
  39. }
  40. public function path(string $name, $extension = '.php'): string
  41. {
  42. if (Str::endsWith($name, '\\')) {
  43. $extension = '';
  44. }
  45. foreach ($this->getAutoloadRules() as $prefix => $prefixPath) {
  46. if ($this->isRootNamespace($prefix) || str_starts_with($name, $prefix)) {
  47. return $prefixPath . str_replace('\\', '/', substr($name, strlen($prefix))) . $extension;
  48. }
  49. }
  50. throw new RuntimeException("Invalid class name: {$name}");
  51. }
  52. protected function isRootNamespace(string $namespace): bool
  53. {
  54. return $namespace === '';
  55. }
  56. protected function getAutoloadRules(): array
  57. {
  58. return data_get(Composer::getJsonContent(), 'autoload.psr-4', []);
  59. }
  60. }