298c20b3b505797c7ddbbf512e19c861cb071a64
[yaffs-website] / web / core / modules / views / src / Entity / View.php
1 <?php
2
3 namespace Drupal\views\Entity;
4
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Config\Entity\ConfigEntityBase;
8 use Drupal\Core\Entity\EntityStorageInterface;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\views\Views;
11 use Drupal\views\ViewEntityInterface;
12
13 /**
14  * Defines a View configuration entity class.
15  *
16  * @ConfigEntityType(
17  *   id = "view",
18  *   label = @Translation("View", context = "View entity type"),
19  *   handlers = {
20  *     "access" = "Drupal\views\ViewAccessControlHandler"
21  *   },
22  *   admin_permission = "administer views",
23  *   entity_keys = {
24  *     "id" = "id",
25  *     "label" = "label",
26  *     "status" = "status"
27  *   },
28  *   config_export = {
29  *     "id",
30  *     "label",
31  *     "module",
32  *     "description",
33  *     "tag",
34  *     "base_table",
35  *     "base_field",
36  *     "core",
37  *     "display",
38  *   }
39  * )
40  */
41 class View extends ConfigEntityBase implements ViewEntityInterface {
42
43   /**
44    * The name of the base table this view will use.
45    *
46    * @var string
47    */
48   protected $base_table = 'node';
49
50   /**
51    * The unique ID of the view.
52    *
53    * @var string
54    */
55   protected $id = NULL;
56
57   /**
58    * The label of the view.
59    */
60   protected $label;
61
62   /**
63    * The description of the view, which is used only in the interface.
64    *
65    * @var string
66    */
67   protected $description = '';
68
69   /**
70    * The "tags" of a view.
71    *
72    * The tags are stored as a single string, though it is used as multiple tags
73    * for example in the views overview.
74    *
75    * @var string
76    */
77   protected $tag = '';
78
79   /**
80    * The core version the view was created for.
81    *
82    * @var string
83    */
84   protected $core = \Drupal::CORE_COMPATIBILITY;
85
86   /**
87    * Stores all display handlers of this view.
88    *
89    * An array containing Drupal\views\Plugin\views\display\DisplayPluginBase
90    * objects.
91    *
92    * @var array
93    */
94   protected $display = [];
95
96   /**
97    * The name of the base field to use.
98    *
99    * @var string
100    */
101   protected $base_field = 'nid';
102
103   /**
104    * Stores a reference to the executable version of this view.
105    *
106    * @var \Drupal\views\ViewExecutable
107    */
108   protected $executable;
109
110   /**
111    * The module implementing this view.
112    *
113    * @var string
114    */
115   protected $module = 'views';
116
117   /**
118    * {@inheritdoc}
119    */
120   public function getExecutable() {
121     // Ensure that an executable View is available.
122     if (!isset($this->executable)) {
123       $this->executable = Views::executableFactory()->get($this);
124     }
125
126     return $this->executable;
127   }
128
129   /**
130    * {@inheritdoc}
131    */
132   public function createDuplicate() {
133     $duplicate = parent::createDuplicate();
134     unset($duplicate->executable);
135     return $duplicate;
136   }
137
138   /**
139    * {@inheritdoc}
140    */
141   public function label() {
142     if (!$label = $this->get('label')) {
143       $label = $this->id();
144     }
145     return $label;
146   }
147
148   /**
149    * {@inheritdoc}
150    */
151   public function addDisplay($plugin_id = 'page', $title = NULL, $id = NULL) {
152     if (empty($plugin_id)) {
153       return FALSE;
154     }
155
156     $plugin = Views::pluginManager('display')->getDefinition($plugin_id);
157
158     if (empty($plugin)) {
159       $plugin['title'] = t('Broken');
160     }
161
162     if (empty($id)) {
163       $id = $this->generateDisplayId($plugin_id);
164
165       // Generate a unique human-readable name by inspecting the counter at the
166       // end of the previous display ID, e.g., 'page_1'.
167       if ($id !== 'default') {
168         preg_match("/[0-9]+/", $id, $count);
169         $count = $count[0];
170       }
171       else {
172         $count = '';
173       }
174
175       if (empty($title)) {
176         // If there is no title provided, use the plugin title, and if there are
177         // multiple displays, append the count.
178         $title = $plugin['title'];
179         if ($count > 1) {
180           $title .= ' ' . $count;
181         }
182       }
183     }
184
185     $display_options = [
186       'display_plugin' => $plugin_id,
187       'id' => $id,
188       // Cast the display title to a string since it is an object.
189       // @see \Drupal\Core\StringTranslation\TranslatableMarkup
190       'display_title' => (string) $title,
191       'position' => $id === 'default' ? 0 : count($this->display),
192       'display_options' => [],
193     ];
194
195     // Add the display options to the view.
196     $this->display[$id] = $display_options;
197     return $id;
198   }
199
200   /**
201    * Generates a display ID of a certain plugin type.
202    *
203    * @param string $plugin_id
204    *   Which plugin should be used for the new display ID.
205    *
206    * @return string
207    */
208   protected function generateDisplayId($plugin_id) {
209     // 'default' is singular and is unique, so just go with 'default'
210     // for it. For all others, start counting.
211     if ($plugin_id == 'default') {
212       return 'default';
213     }
214     // Initial ID.
215     $id = $plugin_id . '_1';
216     $count = 1;
217
218     // Loop through IDs based upon our style plugin name until
219     // we find one that is unused.
220     while (!empty($this->display[$id])) {
221       $id = $plugin_id . '_' . ++$count;
222     }
223
224     return $id;
225   }
226
227   /**
228    * {@inheritdoc}
229    */
230   public function &getDisplay($display_id) {
231     return $this->display[$display_id];
232   }
233
234   /**
235    * {@inheritdoc}
236    */
237   public function duplicateDisplayAsType($old_display_id, $new_display_type) {
238     $executable = $this->getExecutable();
239     $display = $executable->newDisplay($new_display_type);
240     $new_display_id = $display->display['id'];
241     $displays = $this->get('display');
242
243     // Let the display title be generated by the addDisplay method and set the
244     // right display plugin, but keep the rest from the original display.
245     $display_duplicate = $displays[$old_display_id];
246     unset($display_duplicate['display_title']);
247     unset($display_duplicate['display_plugin']);
248
249     $displays[$new_display_id] = NestedArray::mergeDeep($displays[$new_display_id], $display_duplicate);
250     $displays[$new_display_id]['id'] = $new_display_id;
251
252     // First set the displays.
253     $this->set('display', $displays);
254
255     // Ensure that we just copy display options, which are provided by the new
256     // display plugin.
257     $executable->setDisplay($new_display_id);
258
259     $executable->display_handler->filterByDefinedOptions($displays[$new_display_id]['display_options']);
260     // Update the display settings.
261     $this->set('display', $displays);
262
263     return $new_display_id;
264   }
265
266   /**
267    * {@inheritdoc}
268    */
269   public function calculateDependencies() {
270     parent::calculateDependencies();
271
272     // Ensure that the view is dependant on the module that implements the view.
273     $this->addDependency('module', $this->module);
274
275     $executable = $this->getExecutable();
276     $executable->initDisplay();
277     $executable->initStyle();
278
279     foreach ($executable->displayHandlers as $display) {
280       // Calculate the dependencies each display has.
281       $this->calculatePluginDependencies($display);
282     }
283
284     return $this;
285   }
286
287   /**
288    * {@inheritdoc}
289    */
290   public function preSave(EntityStorageInterface $storage) {
291     parent::preSave($storage);
292
293     // Sort the displays.
294     $display = $this->get('display');
295     ksort($display);
296     $this->set('display', ['default' => $display['default']] + $display);
297
298     // @todo Check whether isSyncing is needed.
299     if (!$this->isSyncing()) {
300       $this->addCacheMetadata();
301     }
302   }
303
304   /**
305    * Fills in the cache metadata of this view.
306    *
307    * Cache metadata is set per view and per display, and ends up being stored in
308    * the view's configuration. This allows Views to determine very efficiently:
309    * - the max-age
310    * - the cache contexts
311    * - the cache tags
312    *
313    * In other words: this allows us to do the (expensive) work of initializing
314    * Views plugins and handlers to determine their effect on the cacheability of
315    * a view at save time rather than at runtime.
316    */
317   protected function addCacheMetadata() {
318     $executable = $this->getExecutable();
319
320     $current_display = $executable->current_display;
321     $displays = $this->get('display');
322     foreach (array_keys($displays) as $display_id) {
323       $display =& $this->getDisplay($display_id);
324       $executable->setDisplay($display_id);
325
326       $cache_metadata = $executable->getDisplay()->calculateCacheMetadata();
327       $display['cache_metadata']['max-age'] = $cache_metadata->getCacheMaxAge();
328       $display['cache_metadata']['contexts'] = $cache_metadata->getCacheContexts();
329       $display['cache_metadata']['tags'] = $cache_metadata->getCacheTags();
330       // Always include at least the 'languages:' context as there will most
331       // probably be translatable strings in the view output.
332       $display['cache_metadata']['contexts'] = Cache::mergeContexts($display['cache_metadata']['contexts'], ['languages:' . LanguageInterface::TYPE_INTERFACE]);
333     }
334     // Restore the previous active display.
335     $executable->setDisplay($current_display);
336   }
337
338   /**
339    * {@inheritdoc}
340    */
341   public function postSave(EntityStorageInterface $storage, $update = TRUE) {
342     parent::postSave($storage, $update);
343
344     // @todo Remove if views implements a view_builder controller.
345     views_invalidate_cache();
346     $this->invalidateCaches();
347
348     // Rebuild the router if this is a new view, or it's status changed.
349     if (!isset($this->original) || ($this->status() != $this->original->status())) {
350       \Drupal::service('router.builder')->setRebuildNeeded();
351     }
352   }
353
354   /**
355    * {@inheritdoc}
356    */
357   public static function postLoad(EntityStorageInterface $storage, array &$entities) {
358     parent::postLoad($storage, $entities);
359     foreach ($entities as $entity) {
360       $entity->mergeDefaultDisplaysOptions();
361     }
362   }
363
364   /**
365    * {@inheritdoc}
366    */
367   public static function preCreate(EntityStorageInterface $storage, array &$values) {
368     parent::preCreate($storage, $values);
369
370     // If there is no information about displays available add at least the
371     // default display.
372     $values += [
373       'display' => [
374         'default' => [
375           'display_plugin' => 'default',
376           'id' => 'default',
377           'display_title' => 'Master',
378           'position' => 0,
379           'display_options' => [],
380         ],
381       ]
382     ];
383   }
384
385   /**
386    * {@inheritdoc}
387    */
388   public function postCreate(EntityStorageInterface $storage) {
389     parent::postCreate($storage);
390
391     $this->mergeDefaultDisplaysOptions();
392   }
393
394   /**
395    * {@inheritdoc}
396    */
397   public static function preDelete(EntityStorageInterface $storage, array $entities) {
398     parent::preDelete($storage, $entities);
399
400     // Call the remove() hook on the individual displays.
401     /** @var \Drupal\views\ViewEntityInterface $entity */
402     foreach ($entities as $entity) {
403       $executable = Views::executableFactory()->get($entity);
404       foreach ($entity->get('display') as $display_id => $display) {
405         $executable->setDisplay($display_id);
406         $executable->getDisplay()->remove();
407       }
408     }
409   }
410
411   /**
412    * {@inheritdoc}
413    */
414   public static function postDelete(EntityStorageInterface $storage, array $entities) {
415     parent::postDelete($storage, $entities);
416
417     $tempstore = \Drupal::service('user.shared_tempstore')->get('views');
418     foreach ($entities as $entity) {
419       $tempstore->delete($entity->id());
420     }
421   }
422
423   /**
424    * {@inheritdoc}
425    */
426   public function mergeDefaultDisplaysOptions() {
427     $displays = [];
428     foreach ($this->get('display') as $key => $options) {
429       $options += [
430         'display_options' => [],
431         'display_plugin' => NULL,
432         'id' => NULL,
433         'display_title' => '',
434         'position' => NULL,
435       ];
436       // Add the defaults for the display.
437       $displays[$key] = $options;
438     }
439     $this->set('display', $displays);
440   }
441
442   /**
443    * {@inheritdoc}
444    */
445   public function isInstallable() {
446     $table_definition = \Drupal::service('views.views_data')->get($this->base_table);
447     // Check whether the base table definition exists and contains a base table
448     // definition. For example, taxonomy_views_data_alter() defines
449     // node_field_data even if it doesn't exist as a base table.
450     return $table_definition && isset($table_definition['table']['base']);
451   }
452
453   /**
454    * {@inheritdoc}
455    */
456   public function __sleep() {
457     $keys = parent::__sleep();
458     unset($keys[array_search('executable', $keys)]);
459     return $keys;
460   }
461
462   /**
463    * Invalidates cache tags.
464    */
465   public function invalidateCaches() {
466     // Invalidate cache tags for cached rows.
467     $tags = $this->getCacheTags();
468     \Drupal::service('cache_tags.invalidator')->invalidateTags($tags);
469   }
470
471 }