3 namespace Drupal\views\Plugin\views\cache;
5 use Drupal\Core\Cache\Cache;
6 use Drupal\Core\Cache\CacheableMetadata;
7 use Drupal\views\Plugin\views\PluginBase;
8 use Drupal\Core\Database\Query\Select;
9 use Drupal\views\ResultRow;
12 * @defgroup views_cache_plugins Views cache plugins
14 * Plugins to handle Views caches.
16 * Cache plugins control how caching is done in Views.
18 * Cache plugins extend \Drupal\views\Plugin\views\cache\CachePluginBase.
19 * They must be annotated with \Drupal\views\Annotation\ViewsCache
20 * annotation, and must be in namespace directory Plugin\views\cache.
22 * @ingroup views_plugins
27 * The base plugin to handle caching.
29 abstract class CachePluginBase extends PluginBase {
32 * Contains all data that should be written/read from cache.
37 * Which cache bin to store query results in.
41 protected $resultsBin = 'data';
44 * Stores the cache ID used for the results cache.
46 * The cache ID is stored in generateResultsKey() got executed.
50 * @see \Drupal\views\Plugin\views\cache\CachePluginBase::generateResultsKey()
52 protected $resultsKey;
55 * Returns the resultsKey property.
58 * The resultsKey property.
60 public function getResultsKey() {
61 return $this->resultsKey;
65 * Return a string to display as the clickable title for the
68 public function summaryTitle() {
69 return $this->t('Unknown');
73 * Determine the expiration time of the cache type, or NULL if no expire.
75 * Plugins must override this to implement expiration.
78 * The cache type, either 'query', 'result'.
80 protected function cacheExpire($type) {
84 * Determine expiration time in the cache table of the cache type
85 * or CACHE_PERMANENT if item shouldn't be removed automatically from cache.
87 * Plugins must override this to implement expiration in the cache table.
90 * The cache type, either 'query', 'result'.
92 protected function cacheSetMaxAge($type) {
93 return Cache::PERMANENT;
97 * Save data to the cache.
99 * A plugin should override this to provide specialized caching behavior.
101 public function cacheSet($type) {
104 // Not supported currently, but this is certainly where we'd put it.
108 'result' => $this->prepareViewResult($this->view->result),
109 'total_rows' => isset($this->view->total_rows) ? $this->view->total_rows : 0,
110 'current_page' => $this->view->getCurrentPage(),
112 $expire = ($this->cacheSetMaxAge($type) === Cache::PERMANENT) ? Cache::PERMANENT : (int) $this->view->getRequest()->server->get('REQUEST_TIME') + $this->cacheSetMaxAge($type);
113 \Drupal::cache($this->resultsBin)->set($this->generateResultsKey(), $data, $expire, $this->getCacheTags());
119 * Retrieve data from the cache.
121 * A plugin should override this to provide specialized caching behavior.
123 public function cacheGet($type) {
124 $cutoff = $this->cacheExpire($type);
127 // Not supported currently, but this is certainly where we'd put it.
130 // Values to set: $view->result, $view->total_rows, $view->execute_time,
131 // $view->current_page.
132 if ($cache = \Drupal::cache($this->resultsBin)->get($this->generateResultsKey())) {
133 if (!$cutoff || $cache->created > $cutoff) {
134 $this->view->result = $cache->data['result'];
135 // Load entities for each result.
136 $this->view->query->loadEntities($this->view->result);
137 $this->view->total_rows = $cache->data['total_rows'];
138 $this->view->setCurrentPage($cache->data['current_page'], TRUE);
139 $this->view->execute_time = 0;
148 * Clear out cached data for a view.
150 public function cacheFlush() {
151 Cache::invalidateTags($this->view->storage->getCacheTagsToInvalidate());
155 * Post process any rendered data.
157 * This can be valuable to be able to cache a view and still have some level of
158 * dynamic output. In an ideal world, the actual output will include HTML
159 * comment based tokens, and then the post process can replace those tokens.
161 * Example usage. If it is known that the view is a node view and that the
162 * primary field will be a nid, you can do something like this:
164 * <!--post-FIELD-NID-->
166 * And then in the post render, create an array with the text that should
169 * strtr($output, array('<!--post-FIELD-1-->', 'output for FIELD of nid 1');
171 * All of the cached result data will be available in $view->result, as well,
172 * so all ids used in the query should be discoverable.
174 public function postRender(&$output) { }
177 * Calculates and sets a cache ID used for the result cache.
180 * The generated cache ID.
182 public function generateResultsKey() {
183 if (!isset($this->resultsKey)) {
184 $build_info = $this->view->build_info;
186 foreach (['query', 'count_query'] as $index) {
187 // If the default query back-end is used generate SQL query strings from
188 // the query objects.
189 if ($build_info[$index] instanceof Select) {
190 $query = clone $build_info[$index];
191 $query->preExecute();
192 $build_info[$index] = [
193 'query' => (string)$query,
194 'arguments' => $query->getArguments(),
200 'build_info' => $build_info,
202 // @todo https://www.drupal.org/node/2433591 might solve it to not require
203 // the pager information here.
204 $key_data['pager'] = [
205 'page' => $this->view->getCurrentPage(),
206 'items_per_page' => $this->view->getItemsPerPage(),
207 'offset' => $this->view->getOffset(),
209 $key_data += \Drupal::service('cache_contexts_manager')->convertTokensToKeys($this->displayHandler->getCacheMetadata()->getCacheContexts())->getKeys();
211 $this->resultsKey = $this->view->storage->id() . ':' . $this->displayHandler->display['id'] . ':results:' . hash('sha256', serialize($key_data));
214 return $this->resultsKey;
218 * Gets an array of cache tags for the current view.
221 * An array of cache tags based on the current view.
223 public function getCacheTags() {
224 $tags = $this->view->storage->getCacheTags();
226 // The list cache tags for the entity types listed in this view.
227 $entity_information = $this->view->getQuery()->getEntityTableInfo();
229 if (!empty($entity_information)) {
230 // Add the list cache tags for each entity type used by this view.
231 foreach ($entity_information as $table => $metadata) {
232 $tags = Cache::mergeTags($tags, \Drupal::entityManager()->getDefinition($metadata['entity_type'])->getListCacheTags());
236 $tags = Cache::mergeTags($tags, $this->view->getQuery()->getCacheTags());
242 * Gets the max age for the current view.
246 public function getCacheMaxAge() {
247 $max_age = $this->getDefaultCacheMaxAge();
248 $max_age = Cache::mergeMaxAges($max_age, $this->view->getQuery()->getCacheMaxAge());
253 * Returns the default cache max age.
255 protected function getDefaultCacheMaxAge() {
256 // The default cache backend is not caching anything.
261 * Prepares the view result before putting it into cache.
263 * @param \Drupal\views\ResultRow[] $result
264 * The result containing loaded entities.
266 * @return \Drupal\views\ResultRow[]
267 * The result without loaded entities.
269 protected function prepareViewResult(array $result) {
272 // Clone each row object and remove any loaded entities, to keep the
273 // original result rows intact.
274 foreach ($result as $key => $row) {
276 $clone->resetEntityData();
277 $return[$key] = $clone;
284 * Alters the cache metadata of a display upon saving a view.
286 * @param \Drupal\Core\Cache\CacheableMetadata $cache_metadata
287 * The cache metadata.
289 public function alterCacheMetadata(CacheableMetadata $cache_metadata) {
293 * Returns the row cache tags.
295 * @param ResultRow $row
299 * The row cache tags.
301 public function getRowCacheTags(ResultRow $row) {
302 $tags = !empty($row->_entity) ? $row->_entity->getCacheTags() : [];
304 if (!empty($row->_relationship_entities)) {
305 foreach ($row->_relationship_entities as $entity) {
306 $tags = Cache::mergeTags($tags, $entity->getCacheTags());
314 * Returns the row cache keys.
316 * @param \Drupal\views\ResultRow $row
320 * The row cache keys.
322 public function getRowCacheKeys(ResultRow $row) {
327 $this->view->current_display,
328 $this->getRowId($row),
333 * Returns a unique identifier for the specified row.
335 * @param \Drupal\views\ResultRow $row
339 * The row identifier.
341 public function getRowId(ResultRow $row) {
342 // Here we compute a unique identifier for the row by computing the hash of
343 // its data. We exclude the current index, since the same row could have a
344 // different result index depending on the user permissions. We exclude also
345 // entity data, since serializing entity objects is very expensive. Instead
346 // we include entity cache tags, which are enough to identify all the
347 // entities associated with the row.
348 $row_data = array_diff_key((array) $row, array_flip(['index', '_entity', '_relationship_entities'])) + $this->getRowCacheTags($row);
350 // This ensures that we get a unique identifier taking field handler access
351 // into account: users having access to different sets of fields will get
352 // different row identifiers.
353 $field_ids = array_keys($this->view->field);
354 $row_data += array_flip($field_ids);
356 // Finally we compute a hash of row data and return it as row identifier.
357 return hash('sha256', serialize($row_data));