AbstractPackageCollection.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. namespace Grav\Common\GPM\Remote;
  3. use Grav\Common\GPM\Common\AbstractPackageCollection as BaseCollection;
  4. use Grav\Common\GPM\Response;
  5. use \Doctrine\Common\Cache\FilesystemCache;
  6. class AbstractPackageCollection extends BaseCollection
  7. {
  8. /**
  9. * The cached data previously fetched
  10. * @var string
  11. */
  12. protected $raw;
  13. /**
  14. * The lifetime to store the entry in seconds
  15. * @var integer
  16. */
  17. private $lifetime = 86400;
  18. protected $repository;
  19. protected $cache;
  20. public function __construct($repository = null, $refresh = false, $callback = null)
  21. {
  22. if ($repository === null) {
  23. throw new \RuntimeException("A repository is required to indicate the origin of the remote collection");
  24. }
  25. $cache_dir = self::getGrav()['locator']->findResource('cache://gpm', true, true);
  26. $this->cache = new FilesystemCache($cache_dir);
  27. $this->repository = $repository;
  28. $this->raw = $this->cache->fetch(md5($this->repository));
  29. $this->fetch($refresh, $callback);
  30. foreach (json_decode($this->raw, true) as $slug => $data) {
  31. $this->items[$slug] = new Package($data, $this->type);
  32. }
  33. }
  34. public function fetch($refresh = false, $callback = null)
  35. {
  36. if (!$this->raw || $refresh) {
  37. $response = Response::get($this->repository, [], $callback);
  38. $this->raw = $response;
  39. $this->cache->save(md5($this->repository), $this->raw, $this->lifetime);
  40. }
  41. return $this->raw;
  42. }
  43. }