Composer.php 1.4 KB

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