Composer.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace Dcat\Admin\Support;
  3. use Composer\Autoload\ClassLoader;
  4. class Composer
  5. {
  6. /**
  7. * @var array
  8. */
  9. protected static $files = [];
  10. /**
  11. * @var ClassLoader
  12. */
  13. protected static $loader;
  14. /**
  15. * 获取 composer 类加载器.
  16. *
  17. * @return ClassLoader
  18. */
  19. public static function loader()
  20. {
  21. if (! static::$loader) {
  22. static::$loader = include base_path().'/vendor/autoload.php';
  23. }
  24. return static::$loader;
  25. }
  26. /**
  27. * @param $path
  28. * @return ComposerProperty
  29. */
  30. public static function parse(?string $path)
  31. {
  32. return new ComposerProperty(static::fromJson($path));
  33. }
  34. /**
  35. * @param null|string $packageName
  36. * @param null|string $lockFile
  37. * @return null
  38. */
  39. public static function getVersion(?string $packageName, ?string $lockFile = null)
  40. {
  41. if (! $packageName) {
  42. return null;
  43. }
  44. $lockFile = $lockFile ?: base_path('composer.lock');
  45. $content = collect(static::fromJson($lockFile)['packages'] ?? [])
  46. ->filter(function ($value) use ($packageName) {
  47. return $value['name'] == $packageName;
  48. })->first();
  49. return $content['version'] ?? null;
  50. }
  51. /**
  52. * @param null|string $path
  53. * @return array
  54. */
  55. public static function fromJson(?string $path)
  56. {
  57. if (isset(static::$files[$path])) {
  58. return static::$files[$path];
  59. }
  60. if (! $path || ! is_file($path)) {
  61. return static::$files[$path] = [];
  62. }
  63. try {
  64. return static::$files[$path] = (array) json_decode(app('files')->get($path), true);
  65. } catch (\Throwable $e) {
  66. }
  67. return static::$files[$path] = [];
  68. }
  69. }