Adapter.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. <?php
  2. namespace League\Flysystem\Cached\Storage;
  3. use League\Flysystem\AdapterInterface;
  4. use League\Flysystem\Config;
  5. class Adapter extends AbstractCache
  6. {
  7. /**
  8. * @var AdapterInterface An adapter
  9. */
  10. protected $adapter;
  11. /**
  12. * @var string the file to cache to
  13. */
  14. protected $file;
  15. /**
  16. * @var int|null seconds until cache expiration
  17. */
  18. protected $expire = null;
  19. /**
  20. * Constructor.
  21. *
  22. * @param AdapterInterface $adapter adapter
  23. * @param string $file the file to cache to
  24. * @param int|null $expire seconds until cache expiration
  25. */
  26. public function __construct(AdapterInterface $adapter, $file, $expire = null)
  27. {
  28. $this->adapter = $adapter;
  29. $this->file = $file;
  30. $this->setExpire($expire);
  31. }
  32. /**
  33. * Set the expiration time in seconds.
  34. *
  35. * @param int $expire relative expiration time
  36. */
  37. protected function setExpire($expire)
  38. {
  39. if ($expire) {
  40. $this->expire = $this->getTime($expire);
  41. }
  42. }
  43. /**
  44. * Get expiration time in seconds.
  45. *
  46. * @param int $time relative expiration time
  47. *
  48. * @return int actual expiration time
  49. */
  50. protected function getTime($time = 0)
  51. {
  52. return intval(microtime(true)) + $time;
  53. }
  54. /**
  55. * {@inheritdoc}
  56. */
  57. public function setFromStorage($json)
  58. {
  59. list($cache, $complete, $expire) = json_decode($json, true);
  60. if (! $expire || $expire > $this->getTime()) {
  61. $this->cache = $cache;
  62. $this->complete = $complete;
  63. } else {
  64. $this->adapter->delete($this->file);
  65. }
  66. }
  67. /**
  68. * {@inheritdoc}
  69. */
  70. public function load()
  71. {
  72. if ($this->adapter->has($this->file)) {
  73. $file = $this->adapter->read($this->file);
  74. if ($file && !empty($file['contents'])) {
  75. $this->setFromStorage($file['contents']);
  76. }
  77. }
  78. }
  79. /**
  80. * {@inheritdoc}
  81. */
  82. public function getForStorage()
  83. {
  84. $cleaned = $this->cleanContents($this->cache);
  85. return json_encode([$cleaned, $this->complete, $this->expire]);
  86. }
  87. /**
  88. * {@inheritdoc}
  89. */
  90. public function save()
  91. {
  92. $config = new Config();
  93. $contents = $this->getForStorage();
  94. if ($this->adapter->has($this->file)) {
  95. $this->adapter->update($this->file, $contents, $config);
  96. } else {
  97. $this->adapter->write($this->file, $contents, $config);
  98. }
  99. }
  100. }