AbstractPackageCollection.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. /**
  3. * @package Grav\Common\GPM
  4. *
  5. * @copyright Copyright (c) 2015 - 2022 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\GPM\Remote;
  9. use Grav\Common\Grav;
  10. use Grav\Common\HTTP\Response;
  11. use Grav\Common\GPM\Common\AbstractPackageCollection as BaseCollection;
  12. use \Doctrine\Common\Cache\FilesystemCache;
  13. use RuntimeException;
  14. /**
  15. * Class AbstractPackageCollection
  16. * @package Grav\Common\GPM\Remote
  17. */
  18. class AbstractPackageCollection extends BaseCollection
  19. {
  20. /** @var string The cached data previously fetched */
  21. protected $raw;
  22. /** @var string */
  23. protected $repository;
  24. /** @var FilesystemCache */
  25. protected $cache;
  26. /** @var int The lifetime to store the entry in seconds */
  27. private $lifetime = 86400;
  28. /**
  29. * AbstractPackageCollection constructor.
  30. *
  31. * @param string|null $repository
  32. * @param bool $refresh
  33. * @param callable|null $callback
  34. */
  35. public function __construct($repository = null, $refresh = false, $callback = null)
  36. {
  37. parent::__construct();
  38. if ($repository === null) {
  39. throw new RuntimeException('A repository is required to indicate the origin of the remote collection');
  40. }
  41. $channel = Grav::instance()['config']->get('system.gpm.releases', 'stable');
  42. $cache_dir = Grav::instance()['locator']->findResource('cache://gpm', true, true);
  43. $this->cache = new FilesystemCache($cache_dir);
  44. $this->repository = $repository . '?v=' . GRAV_VERSION . '&' . $channel . '=1';
  45. $this->raw = $this->cache->fetch(md5($this->repository));
  46. $this->fetch($refresh, $callback);
  47. foreach (json_decode($this->raw, true) as $slug => $data) {
  48. // Temporarily fix for using multi-sites
  49. if (isset($data['install_path'])) {
  50. $path = preg_replace('~^user/~i', 'user://', $data['install_path']);
  51. $data['install_path'] = Grav::instance()['locator']->findResource($path, false, true);
  52. }
  53. $this->items[$slug] = new Package($data, $this->type);
  54. }
  55. }
  56. /**
  57. * @param bool $refresh
  58. * @param callable|null $callback
  59. * @return string
  60. */
  61. public function fetch($refresh = false, $callback = null)
  62. {
  63. if (!$this->raw || $refresh) {
  64. $response = Response::get($this->repository, [], $callback);
  65. $this->raw = $response;
  66. $this->cache->save(md5($this->repository), $this->raw, $this->lifetime);
  67. }
  68. return $this->raw;
  69. }
  70. }