Project.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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\Utils\CodeGen;
  12. use Hyperf\Utils\Composer;
  13. use Hyperf\Utils\Str;
  14. /**
  15. * Read composer.json autoload psr-4 rules to figure out the namespace or path.
  16. */
  17. class Project
  18. {
  19. public function namespace(string $path): string
  20. {
  21. $ext = pathinfo($path, PATHINFO_EXTENSION);
  22. if ($ext !== '') {
  23. $path = substr($path, 0, -(strlen($ext) + 1));
  24. } else {
  25. $path = trim($path, '/') . '/';
  26. }
  27. foreach ($this->getAutoloadRules() as $prefix => $prefixPath) {
  28. if ($this->isRootNamespace($prefix) || strpos($path, $prefixPath) === 0) {
  29. return $prefix . str_replace('/', '\\', substr($path, strlen($prefixPath)));
  30. }
  31. }
  32. throw new \RuntimeException("Invalid project path: {$path}");
  33. }
  34. public function className(string $path): string
  35. {
  36. return $this->namespace($path);
  37. }
  38. public function path(string $name, $extension = '.php'): string
  39. {
  40. if (Str::endsWith($name, '\\')) {
  41. $extension = '';
  42. }
  43. foreach ($this->getAutoloadRules() as $prefix => $prefixPath) {
  44. if ($this->isRootNamespace($prefix) || strpos($name, $prefix) === 0) {
  45. return $prefixPath . str_replace('\\', '/', substr($name, strlen($prefix))) . $extension;
  46. }
  47. }
  48. throw new \RuntimeException("Invalid class name: {$name}");
  49. }
  50. protected function isRootNamespace(string $namespace): bool
  51. {
  52. return $namespace === '';
  53. }
  54. protected function getAutoloadRules(): array
  55. {
  56. return data_get(Composer::getJsonContent(), 'autoload.psr-4', []);
  57. }
  58. }