summaryrefslogtreecommitdiffstatshomepage
path: root/core/lib/Drupal/Core/Cache/PhpBackend.php
blob: 9305d3bdde2a00881ea72a57d0f76270b766dd46 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
<?php

namespace Drupal\Core\Cache;

use Drupal\Component\Assertion\Inspector;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Component\PhpStorage\PhpStorageInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\PhpStorage\PhpStorageFactory;

/**
 * Defines a PHP cache implementation.
 *
 * Stores cache items in a PHP file using a storage that implements
 * Drupal\Component\PhpStorage\PhpStorageInterface.
 *
 * This is fast because of PHP's opcode caching mechanism. Once a file's
 * content is stored in PHP's opcode cache, including it doesn't require
 * reading the contents from a filesystem. Instead, PHP will use the already
 * compiled opcodes stored in memory.
 *
 * @ingroup cache
 */
class PhpBackend implements CacheBackendInterface {

  /**
   * @var string
   */
  protected $bin;

  /**
   * The PHP storage.
   */
  protected PhpStorageInterface $storage;

  /**
   * Array to store cache objects.
   *
   * @var object[]
   */
  protected $cache = [];

  /**
   * The cache tags checksum provider.
   *
   * @var \Drupal\Core\Cache\CacheTagsChecksumInterface
   */
  protected $checksumProvider;

  /**
   * Constructs a PhpBackend object.
   *
   * @param string $bin
   *   The cache bin for which the object is created.
   * @param \Drupal\Core\Cache\CacheTagsChecksumInterface $checksum_provider
   *   The cache tags checksum provider.
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The time service.
   */
  public function __construct($bin, CacheTagsChecksumInterface $checksum_provider, protected TimeInterface $time) {
    $this->bin = 'cache_' . $bin;
    $this->checksumProvider = $checksum_provider;
  }

  /**
   * {@inheritdoc}
   */
  public function get($cid, $allow_invalid = FALSE) {
    return $this->getByHash($this->normalizeCid($cid), $allow_invalid);
  }

  /**
   * Fetch a cache item using a hashed cache ID.
   *
   * @param string $cidhash
   *   The hashed version of the original cache ID after being normalized.
   * @param bool $allow_invalid
   *   (optional) If TRUE, a cache item may be returned even if it is expired or
   *   has been invalidated.
   *
   * @return bool|mixed
   *   The requested cached item. Defaults to FALSE when the cache is not set.
   */
  protected function getByHash($cidhash, $allow_invalid = FALSE) {
    if ($file = $this->storage()->getFullPath($cidhash)) {
      $cache = @include $file;
    }
    if (isset($cache)) {
      return $this->prepareItem($cache, $allow_invalid);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public function setMultiple(array $items) {
    foreach ($items as $cid => $item) {
      $this->set($cid, $item['data'], $item['expire'] ?? CacheBackendInterface::CACHE_PERMANENT, $item['tags'] ?? []);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getMultiple(&$cids, $allow_invalid = FALSE) {
    $ret = [];

    foreach ($cids as $cid) {
      if ($item = $this->get($cid, $allow_invalid)) {
        $ret[$item->cid] = $item;
      }
    }

    $cids = array_diff($cids, array_keys($ret));

    return $ret;
  }

  /**
   * Prepares a cached item.
   *
   * Checks that items are either permanent or did not expire, and returns data
   * as appropriate.
   *
   * @param object $cache
   *   An item loaded from self::get() or self::getMultiple().
   * @param bool $allow_invalid
   *   If FALSE, the method returns FALSE if the cache item is not valid.
   *
   * @return mixed
   *   The item with data as appropriate or FALSE if there is no
   *   valid item to load.
   */
  protected function prepareItem($cache, $allow_invalid) {
    if (!isset($cache->data)) {
      return FALSE;
    }

    // Check expire time.
    $cache->valid = $cache->expire == Cache::PERMANENT || $cache->expire >= $this->time->getRequestTime();

    // Check if invalidateTags() has been called with any of the item's tags.
    if (!$this->checksumProvider->isValid($cache->checksum, $cache->tags)) {
      $cache->valid = FALSE;
    }

    if (!$allow_invalid && !$cache->valid) {
      return FALSE;
    }

    return $cache;
  }

  /**
   * {@inheritdoc}
   */
  public function set($cid, $data, $expire = Cache::PERMANENT, array $tags = []) {
    assert(Inspector::assertAllStrings($tags), 'Cache Tags must be strings.');

    $item = (object) [
      'cid' => $cid,
      'data' => $data,
      'created' => round(microtime(TRUE), 3),
      'expire' => $expire,
      'tags' => array_unique($tags),
      'checksum' => $this->checksumProvider->getCurrentChecksum($tags),
    ];
    $this->writeItem($this->normalizeCid($cid), $item);
  }

  /**
   * {@inheritdoc}
   */
  public function delete($cid) {
    $this->storage()->delete($this->normalizeCid($cid));
  }

  /**
   * {@inheritdoc}
   */
  public function deleteMultiple(array $cids) {
    foreach ($cids as $cid) {
      $this->delete($cid);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function deleteAll() {
    $this->storage()->deleteAll();
  }

  /**
   * {@inheritdoc}
   */
  public function invalidate($cid) {
    $this->invalidateByHash($this->normalizeCid($cid));
  }

  /**
   * Invalidate one cache item.
   *
   * @param string $cidhash
   *   The hashed version of the original cache ID after being normalized.
   */
  protected function invalidateByHash($cidhash) {
    if ($item = $this->getByHash($cidhash)) {
      $item->expire = $this->time->getRequestTime() - 1;
      $this->writeItem($cidhash, $item);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function invalidateMultiple(array $cids) {
    foreach ($cids as $cid) {
      $this->invalidate($cid);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function invalidateAll() {
    @trigger_error("CacheBackendInterface::invalidateAll() is deprecated in drupal:11.2.0 and is removed from drupal:12.0.0. Use CacheBackendInterface::deleteAll() or cache tag invalidation instead. See https://www.drupal.org/node/3500622", E_USER_DEPRECATED);
    foreach ($this->storage()->listAll() as $cidhash) {
      $this->invalidateByHash($cidhash);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function garbageCollection() {
  }

  /**
   * {@inheritdoc}
   */
  public function removeBin() {
    $this->cache = [];
    $this->storage()->deleteAll();
  }

  /**
   * Writes a cache item to PhpStorage.
   *
   * @param string $cidhash
   *   The hashed version of the original cache ID after being normalized.
   * @param object $item
   *   The cache item to store.
   */
  protected function writeItem($cidhash, \stdClass $item) {
    $content = '<?php return unserialize(' . var_export(serialize($item), TRUE) . ');';
    $this->storage()->save($cidhash, $content);
  }

  /**
   * Gets the PHP code storage object to use.
   *
   * @return \Drupal\Component\PhpStorage\PhpStorageInterface
   *   The PHP storage.
   */
  protected function storage() {
    if (!isset($this->storage)) {
      $this->storage = PhpStorageFactory::get($this->bin);
    }
    return $this->storage;
  }

  /**
   * Ensures a normalized cache ID.
   *
   * @param string $cid
   *   The passed in cache ID.
   *
   * @return string
   *   A normalized cache ID.
   */
  protected function normalizeCid($cid) {
    return Crypt::hashBase64($cid);
  }

}