MemoryCache.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Drupal\Core\Cache\MemoryCache;
  3. use Drupal\Component\Assertion\Inspector;
  4. use Drupal\Core\Cache\MemoryBackend;
  5. /**
  6. * Defines a memory cache implementation.
  7. *
  8. * Stores cache items in memory using a PHP array.
  9. *
  10. * @ingroup cache
  11. */
  12. class MemoryCache extends MemoryBackend implements MemoryCacheInterface {
  13. /**
  14. * Prepares a cached item.
  15. *
  16. * Checks that items are either permanent or did not expire, and returns data
  17. * as appropriate.
  18. *
  19. * @param object $cache
  20. * An item loaded from cache_get() or cache_get_multiple().
  21. * @param bool $allow_invalid
  22. * (optional) If TRUE, cache items may be returned even if they have expired
  23. * or been invalidated. Defaults to FALSE.
  24. *
  25. * @return mixed
  26. * The item with data as appropriate or FALSE if there is no
  27. * valid item to load.
  28. */
  29. protected function prepareItem($cache, $allow_invalid = FALSE) {
  30. if (!isset($cache->data)) {
  31. return FALSE;
  32. }
  33. // Check expire time.
  34. $cache->valid = $cache->expire == static::CACHE_PERMANENT || $cache->expire >= $this->getRequestTime();
  35. if (!$allow_invalid && !$cache->valid) {
  36. return FALSE;
  37. }
  38. return $cache;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function set($cid, $data, $expire = MemoryCacheInterface::CACHE_PERMANENT, array $tags = []) {
  44. assert(Inspector::assertAllStrings($tags), 'Cache tags must be strings.');
  45. $tags = array_unique($tags);
  46. $this->cache[$cid] = (object) [
  47. 'cid' => $cid,
  48. 'data' => $data,
  49. 'created' => $this->getRequestTime(),
  50. 'expire' => $expire,
  51. 'tags' => $tags,
  52. ];
  53. }
  54. }