Further Drupal 8.6.4 changes. Some core files were not committed before a commit...
[yaffs-website] / web / core / modules / views / src / ViewsData.php
1 <?php
2
3 namespace Drupal\views;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Cache\CacheBackendInterface;
8 use Drupal\Core\Config\ConfigFactoryInterface;
9 use Drupal\Core\Extension\ModuleHandlerInterface;
10 use Drupal\Core\Language\LanguageManagerInterface;
11
12 /**
13  * Class to manage and lazy load cached views data.
14  *
15  * If a table is requested and cannot be loaded from cache, all data is then
16  * requested from cache. A table-specific cache entry will then be created for
17  * the requested table based on this cached data. Table data is only rebuilt
18  * when no cache entry for all table data can be retrieved.
19  */
20 class ViewsData {
21
22   /**
23    * The base cache ID to use.
24    *
25    * @var string
26    */
27   protected $baseCid = 'views_data';
28
29   /**
30    * The cache backend to use.
31    *
32    * @var \Drupal\Core\Cache\CacheBackendInterface
33    */
34   protected $cacheBackend;
35
36   /**
37    * Table data storage.
38    *
39    * This is used for explicitly requested tables.
40    *
41    * @var array
42    */
43   protected $storage = [];
44
45   /**
46    * All table storage data loaded from cache.
47    *
48    * This is used when all data has been loaded from the cache to prevent
49    * further cache get calls when rebuilding all data or for single tables.
50    *
51    * @var array
52    */
53   protected $allStorage = [];
54
55   /**
56    * Whether the data has been fully loaded in this request.
57    *
58    * @var bool
59    */
60   protected $fullyLoaded = FALSE;
61
62   /**
63    * Whether or not to skip data caching and rebuild data each time.
64    *
65    * @var bool
66    */
67   protected $skipCache = FALSE;
68
69   /**
70    * The current language code.
71    *
72    * @var string
73    */
74   protected $langcode;
75
76   /**
77    * Stores a module manager to invoke hooks.
78    *
79    * @var \Drupal\Core\Extension\ModuleHandlerInterface
80    */
81   protected $moduleHandler;
82
83   /**
84    * The language manager.
85    *
86    * @var \Drupal\Core\Language\LanguageManagerInterface
87    */
88   protected $languageManager;
89
90   /**
91    * Constructs this ViewsData object.
92    *
93    * @param \Drupal\Core\Cache\CacheBackendInterface $cache_backend
94    *   The cache backend to use.
95    * @param \Drupal\Core\Config\ConfigFactoryInterface $config
96    *   The configuration factory object to use.
97    * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
98    *   The module handler class to use for invoking hooks.
99    * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
100    *   The language manager.
101    */
102   public function __construct(CacheBackendInterface $cache_backend, ConfigFactoryInterface $config, ModuleHandlerInterface $module_handler, LanguageManagerInterface $language_manager) {
103     $this->cacheBackend = $cache_backend;
104     $this->moduleHandler = $module_handler;
105     $this->languageManager = $language_manager;
106
107     $this->langcode = $this->languageManager->getCurrentLanguage()->getId();
108     $this->skipCache = $config->get('views.settings')->get('skip_cache');
109   }
110
111   /**
112    * Gets all table data.
113    *
114    * @see https://www.drupal.org/node/2723553
115    *
116    * @return array
117    *   An array of table data.
118    */
119   public function getAll() {
120     if (!$this->fullyLoaded) {
121       $this->allStorage = $this->getData();
122     }
123
124     // Set storage from allStorage outside of the fullyLoaded check to prevent
125     // cache calls on requests that have requested all data to get a single
126     // tables data. Make sure $this->storage is populated in this case.
127     $this->storage = $this->allStorage;
128     return $this->allStorage;
129   }
130
131   /**
132    * Gets data for a particular table, or all tables.
133    *
134    * @param string|null $key
135    *   The key of the cache entry to retrieve. Defaults to NULL, this will
136    *   return all table data. NULL $key deprecated in Drupal 8.2.x and will be
137    *   removed in 9.0.0. Use getAll() instead.
138    *
139    * @see https://www.drupal.org/node/2723553
140    *
141    * @return array
142    *   An array of table data.
143    */
144   public function get($key = NULL) {
145     if (!$key) {
146       return $this->getAll();
147     }
148     if (!isset($this->storage[$key])) {
149       // Prepare a cache ID for get and set.
150       $cid = $this->baseCid . ':' . $key;
151       $from_cache = FALSE;
152
153       if ($data = $this->cacheGet($cid)) {
154         $this->storage[$key] = $data->data;
155         $from_cache = TRUE;
156       }
157       // If there is no cached entry and data is not already fully loaded,
158       // rebuild. This will stop requests for invalid tables calling getData.
159       elseif (!$this->fullyLoaded) {
160         $this->allStorage = $this->getData();
161       }
162
163       if (!$from_cache) {
164         if (!isset($this->allStorage[$key])) {
165           // Write an empty cache entry if no information for that table
166           // exists to avoid repeated cache get calls for this table and
167           // prevent loading all tables unnecessarily.
168           $this->storage[$key] = [];
169           $this->allStorage[$key] = [];
170         }
171         else {
172           $this->storage[$key] = $this->allStorage[$key];
173         }
174
175         // Create a cache entry for the requested table.
176         $this->cacheSet($cid, $this->allStorage[$key]);
177       }
178     }
179     return $this->storage[$key];
180   }
181
182   /**
183    * Gets data from the cache backend.
184    *
185    * @param string $cid
186    *   The cache ID to return.
187    *
188    * @return mixed
189    *   The cached data, if any. This will immediately return FALSE if the
190    *   $skipCache property is TRUE.
191    */
192   protected function cacheGet($cid) {
193     if ($this->skipCache) {
194       return FALSE;
195     }
196
197     return $this->cacheBackend->get($this->prepareCid($cid));
198   }
199
200   /**
201    * Sets data to the cache backend.
202    *
203    * @param string $cid
204    *   The cache ID to set.
205    * @param mixed $data
206    *   The data that will be cached.
207    */
208   protected function cacheSet($cid, $data) {
209     return $this->cacheBackend->set($this->prepareCid($cid), $data, Cache::PERMANENT, ['views_data', 'config:core.extension']);
210   }
211
212   /**
213    * Prepares the cache ID by appending a language code.
214    *
215    * @param string $cid
216    *   The cache ID to prepare.
217    *
218    * @return string
219    *   The prepared cache ID.
220    */
221   protected function prepareCid($cid) {
222     return $cid . ':' . $this->langcode;
223   }
224
225   /**
226    * Gets all data invoked by hook_views_data().
227    *
228    * This is requested from the cache before being rebuilt.
229    *
230    * @return array
231    *   An array of all data.
232    */
233   protected function getData() {
234     $this->fullyLoaded = TRUE;
235
236     if ($data = $this->cacheGet($this->baseCid)) {
237       return $data->data;
238     }
239     else {
240       $modules = $this->moduleHandler->getImplementations('views_data');
241       $data = [];
242       foreach ($modules as $module) {
243         $views_data = $this->moduleHandler->invoke($module, 'views_data');
244         // Set the provider key for each base table.
245         foreach ($views_data as &$table) {
246           if (isset($table['table']) && !isset($table['table']['provider'])) {
247             $table['table']['provider'] = $module;
248           }
249         }
250         $data = NestedArray::mergeDeep($data, $views_data);
251       }
252       $this->moduleHandler->alter('views_data', $data);
253
254       $this->processEntityTypes($data);
255
256       // Keep a record with all data.
257       $this->cacheSet($this->baseCid, $data);
258
259       return $data;
260     }
261   }
262
263   /**
264    * Links tables with 'entity type' to respective generic entity-type tables.
265    *
266    * @param array $data
267    *   The array of data to alter entity data for, passed by reference.
268    */
269   protected function processEntityTypes(array &$data) {
270     foreach ($data as $table_name => $table_info) {
271       // Add in a join from the entity-table if an entity-type is given.
272       if (!empty($table_info['table']['entity type'])) {
273         $entity_table = 'views_entity_' . $table_info['table']['entity type'];
274
275         $data[$entity_table]['table']['join'][$table_name] = [
276           'left_table' => $table_name,
277         ];
278         $data[$entity_table]['table']['entity type'] = $table_info['table']['entity type'];
279         // Copy over the default table group if we have none yet.
280         if (!empty($table_info['table']['group']) && empty($data[$entity_table]['table']['group'])) {
281           $data[$entity_table]['table']['group'] = $table_info['table']['group'];
282         }
283       }
284     }
285   }
286
287   /**
288    * Fetches a list of all base tables available.
289    *
290    * @return array
291    *   An array of base table data keyed by table name. Each item contains the
292    *   following keys:
293    *     - title: The title label for the base table.
294    *     - help: The help text for the base table.
295    *     - weight: The weight of the base table.
296    */
297   public function fetchBaseTables() {
298     $tables = [];
299
300     foreach ($this->get() as $table => $info) {
301       if (!empty($info['table']['base'])) {
302         $tables[$table] = [
303           'title' => $info['table']['base']['title'],
304           'help' => !empty($info['table']['base']['help']) ? $info['table']['base']['help'] : '',
305           'weight' => !empty($info['table']['base']['weight']) ? $info['table']['base']['weight'] : 0,
306         ];
307       }
308     }
309
310     // Sorts by the 'weight' and then by 'title' element.
311     uasort($tables, function ($a, $b) {
312       if ($a['weight'] != $b['weight']) {
313         return $a['weight'] < $b['weight'] ? -1 : 1;
314       }
315       if ($a['title'] != $b['title']) {
316         return $a['title'] < $b['title'] ? -1 : 1;
317       }
318       return 0;
319     });
320
321     return $tables;
322   }
323
324   /**
325    * Clears the class storage and cache.
326    */
327   public function clear() {
328     $this->storage = [];
329     $this->allStorage = [];
330     $this->fullyLoaded = FALSE;
331     Cache::invalidateTags(['views_data']);
332   }
333
334 }