AbstractPackageCollection.php 2.3 KB

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