Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.
   1  <?php
   2  
   3  namespace Kevinrob\GuzzleCache\Storage;
   4  
   5  use Psr\Cache\CacheItemInterface;
   6  use Psr\Cache\CacheItemPoolInterface;
   7  use Kevinrob\GuzzleCache\CacheEntry;
   8  
   9  class Psr6CacheStorage implements CacheStorageInterface
  10  {
  11      /**
  12       * The cache pool.
  13       *
  14       * @var CacheItemPoolInterface
  15       */
  16      protected $cachePool;
  17  
  18      /**
  19       * The last item retrieved from the cache.
  20       *
  21       * This item is transiently stored so that save() can reuse the cache item
  22       * usually retrieved by fetch() beforehand, instead of requesting it a second time.
  23       *
  24       * @var CacheItemInterface|null
  25       */
  26      protected $lastItem;
  27  
  28      /**
  29       * @param CacheItemPoolInterface $cachePool
  30       */
  31      public function __construct(CacheItemPoolInterface $cachePool)
  32      {
  33          $this->cachePool = $cachePool;
  34      }
  35  
  36      /**
  37       * {@inheritdoc}
  38       */
  39      public function fetch($key)
  40      {
  41          $item = $this->cachePool->getItem($key);
  42          $this->lastItem = $item;
  43  
  44          $cache = $item->get();
  45  
  46          if ($cache instanceof CacheEntry) {
  47              return $cache;
  48          }
  49  
  50          return null;
  51      }
  52  
  53      /**
  54       * {@inheritdoc}
  55       */
  56      public function save($key, CacheEntry $data)
  57      {
  58          if ($this->lastItem && $this->lastItem->getKey() == $key) {
  59              $item = $this->lastItem;
  60          } else {
  61              $item = $this->cachePool->getItem($key);
  62          }
  63  
  64          $this->lastItem = null;
  65  
  66          $item->set($data);
  67  
  68          $ttl = $data->getTTL();
  69          if ($ttl === 0) {
  70              // No expiration
  71              $item->expiresAfter(null);
  72          } else {
  73              $item->expiresAfter($ttl);
  74          }
  75  
  76          return $this->cachePool->save($item);
  77      }
  78  
  79      /**
  80       * @param string $key
  81       *
  82       * @return bool
  83       */
  84      public function delete($key)
  85      {
  86          if (null !== $this->lastItem && $this->lastItem->getKey() === $key) {
  87              $this->lastItem = null;
  88          }
  89  
  90          return $this->cachePool->deleteItem($key);
  91      }
  92  }