3 namespace Drupal\views\Entity;
5 use Drupal\Component\Utility\NestedArray;
6 use Drupal\Core\Cache\Cache;
7 use Drupal\Core\Config\Entity\ConfigEntityBase;
8 use Drupal\Core\Entity\ContentEntityTypeInterface;
9 use Drupal\Core\Entity\EntityStorageInterface;
10 use Drupal\Core\Entity\FieldableEntityInterface;
11 use Drupal\Core\Language\LanguageInterface;
12 use Drupal\views\Plugin\DependentWithRemovalPluginInterface;
13 use Drupal\views\Views;
14 use Drupal\views\ViewEntityInterface;
17 * Defines a View configuration entity class.
21 * label = @Translation("View", context = "View entity type"),
22 * admin_permission = "administer views",
41 class View extends ConfigEntityBase implements ViewEntityInterface {
44 * The name of the base table this view will use.
48 protected $base_table = 'node';
51 * The unique ID of the view.
58 * The label of the view.
63 * The description of the view, which is used only in the interface.
67 protected $description = '';
70 * The "tags" of a view.
72 * The tags are stored as a single string, though it is used as multiple tags
73 * for example in the views overview.
80 * The core version the view was created for.
84 protected $core = \Drupal::CORE_COMPATIBILITY;
87 * Stores all display handlers of this view.
89 * An array containing Drupal\views\Plugin\views\display\DisplayPluginBase
94 protected $display = [];
97 * The name of the base field to use.
101 protected $base_field = 'nid';
104 * Stores a reference to the executable version of this view.
106 * @var \Drupal\views\ViewExecutable
108 protected $executable;
111 * The module implementing this view.
115 protected $module = 'views';
120 public function getExecutable() {
121 // Ensure that an executable View is available.
122 if (!isset($this->executable)) {
123 $this->executable = Views::executableFactory()->get($this);
126 return $this->executable;
132 public function createDuplicate() {
133 $duplicate = parent::createDuplicate();
134 unset($duplicate->executable);
141 public function label() {
142 if (!$label = $this->get('label')) {
143 $label = $this->id();
151 public function addDisplay($plugin_id = 'page', $title = NULL, $id = NULL) {
152 if (empty($plugin_id)) {
156 $plugin = Views::pluginManager('display')->getDefinition($plugin_id);
158 if (empty($plugin)) {
159 $plugin['title'] = t('Broken');
163 $id = $this->generateDisplayId($plugin_id);
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);
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'];
180 $title .= ' ' . $count;
186 'display_plugin' => $plugin_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' => [],
195 // Add the display options to the view.
196 $this->display[$id] = $display_options;
201 * Generates a display ID of a certain plugin type.
203 * @param string $plugin_id
204 * Which plugin should be used for the new display ID.
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') {
215 $id = $plugin_id . '_1';
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;
230 public function &getDisplay($display_id) {
231 return $this->display[$display_id];
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');
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']);
249 $displays[$new_display_id] = NestedArray::mergeDeep($displays[$new_display_id], $display_duplicate);
250 $displays[$new_display_id]['id'] = $new_display_id;
252 // First set the displays.
253 $this->set('display', $displays);
255 // Ensure that we just copy display options, which are provided by the new
257 $executable->setDisplay($new_display_id);
259 $executable->display_handler->filterByDefinedOptions($displays[$new_display_id]['display_options']);
260 // Update the display settings.
261 $this->set('display', $displays);
263 return $new_display_id;
269 public function calculateDependencies() {
270 parent::calculateDependencies();
272 // Ensure that the view is dependant on the module that implements the view.
273 $this->addDependency('module', $this->module);
275 $executable = $this->getExecutable();
276 $executable->initDisplay();
277 $executable->initStyle();
279 foreach ($executable->displayHandlers as $display) {
280 // Calculate the dependencies each display has.
281 $this->calculatePluginDependencies($display);
290 public function preSave(EntityStorageInterface $storage) {
291 parent::preSave($storage);
293 $displays = $this->get('display');
295 $this->fixTableNames($displays);
297 // Sort the displays.
299 $this->set('display', ['default' => $displays['default']] + $displays);
301 // @todo Check whether isSyncing is needed.
302 if (!$this->isSyncing()) {
303 $this->addCacheMetadata();
308 * Fixes table names for revision metadata fields of revisionable entities.
310 * Views for revisionable entity types using revision metadata fields might
311 * be using the wrong table to retrieve the fields after system_update_8300
312 * has moved them correctly to the revision table. This method updates the
313 * views to use the correct tables.
315 * @param array &$displays
316 * An array containing display handlers of a view.
318 * @deprecated in Drupal 8.3.0, will be removed in Drupal 9.0.0.
320 private function fixTableNames(array &$displays) {
321 // Fix wrong table names for entity revision metadata fields.
322 foreach ($displays as $display => $display_data) {
323 if (isset($display_data['display_options']['fields'])) {
324 foreach ($display_data['display_options']['fields'] as $property_name => $property_data) {
325 if (isset($property_data['entity_type']) && isset($property_data['field']) && isset($property_data['table'])) {
326 $entity_type = $this->entityTypeManager()->getDefinition($property_data['entity_type']);
327 // We need to update the table name only for revisionable entity
328 // types, otherwise the view is already using the correct table.
329 if (($entity_type instanceof ContentEntityTypeInterface) && is_subclass_of($entity_type->getClass(), FieldableEntityInterface::class) && $entity_type->isRevisionable()) {
330 $revision_metadata_fields = $entity_type->getRevisionMetadataKeys();
331 // @see \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout()
332 $revision_table = $entity_type->getRevisionTable() ?: $entity_type->id() . '_revision';
334 // Check if this is a revision metadata field and if it uses the
336 if (in_array($property_data['field'], $revision_metadata_fields) && $property_data['table'] != $revision_table) {
337 $displays[$display]['display_options']['fields'][$property_name]['table'] = $revision_table;
347 * Fills in the cache metadata of this view.
349 * Cache metadata is set per view and per display, and ends up being stored in
350 * the view's configuration. This allows Views to determine very efficiently:
352 * - the cache contexts
355 * In other words: this allows us to do the (expensive) work of initializing
356 * Views plugins and handlers to determine their effect on the cacheability of
357 * a view at save time rather than at runtime.
359 protected function addCacheMetadata() {
360 $executable = $this->getExecutable();
362 $current_display = $executable->current_display;
363 $displays = $this->get('display');
364 foreach (array_keys($displays) as $display_id) {
365 $display =& $this->getDisplay($display_id);
366 $executable->setDisplay($display_id);
368 $cache_metadata = $executable->getDisplay()->calculateCacheMetadata();
369 $display['cache_metadata']['max-age'] = $cache_metadata->getCacheMaxAge();
370 $display['cache_metadata']['contexts'] = $cache_metadata->getCacheContexts();
371 $display['cache_metadata']['tags'] = $cache_metadata->getCacheTags();
372 // Always include at least the 'languages:' context as there will most
373 // probably be translatable strings in the view output.
374 $display['cache_metadata']['contexts'] = Cache::mergeContexts($display['cache_metadata']['contexts'], ['languages:' . LanguageInterface::TYPE_INTERFACE]);
376 // Restore the previous active display.
377 $executable->setDisplay($current_display);
383 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
384 parent::postSave($storage, $update);
386 // @todo Remove if views implements a view_builder controller.
387 views_invalidate_cache();
388 $this->invalidateCaches();
390 // Rebuild the router if this is a new view, or it's status changed.
391 if (!isset($this->original) || ($this->status() != $this->original->status())) {
392 \Drupal::service('router.builder')->setRebuildNeeded();
399 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
400 parent::postLoad($storage, $entities);
401 foreach ($entities as $entity) {
402 $entity->mergeDefaultDisplaysOptions();
409 public static function preCreate(EntityStorageInterface $storage, array &$values) {
410 parent::preCreate($storage, $values);
412 // If there is no information about displays available add at least the
417 'display_plugin' => 'default',
419 'display_title' => 'Master',
421 'display_options' => [],
430 public function postCreate(EntityStorageInterface $storage) {
431 parent::postCreate($storage);
433 $this->mergeDefaultDisplaysOptions();
439 public static function preDelete(EntityStorageInterface $storage, array $entities) {
440 parent::preDelete($storage, $entities);
442 // Call the remove() hook on the individual displays.
443 /** @var \Drupal\views\ViewEntityInterface $entity */
444 foreach ($entities as $entity) {
445 $executable = Views::executableFactory()->get($entity);
446 foreach ($entity->get('display') as $display_id => $display) {
447 $executable->setDisplay($display_id);
448 $executable->getDisplay()->remove();
456 public static function postDelete(EntityStorageInterface $storage, array $entities) {
457 parent::postDelete($storage, $entities);
459 $tempstore = \Drupal::service('user.shared_tempstore')->get('views');
460 foreach ($entities as $entity) {
461 $tempstore->delete($entity->id());
468 public function mergeDefaultDisplaysOptions() {
470 foreach ($this->get('display') as $key => $options) {
472 'display_options' => [],
473 'display_plugin' => NULL,
475 'display_title' => '',
478 // Add the defaults for the display.
479 $displays[$key] = $options;
481 $this->set('display', $displays);
487 public function isInstallable() {
488 $table_definition = \Drupal::service('views.views_data')->get($this->base_table);
489 // Check whether the base table definition exists and contains a base table
490 // definition. For example, taxonomy_views_data_alter() defines
491 // node_field_data even if it doesn't exist as a base table.
492 return $table_definition && isset($table_definition['table']['base']);
498 public function __sleep() {
499 $keys = parent::__sleep();
500 unset($keys[array_search('executable', $keys)]);
505 * Invalidates cache tags.
507 public function invalidateCaches() {
508 // Invalidate cache tags for cached rows.
509 $tags = $this->getCacheTags();
510 \Drupal::service('cache_tags.invalidator')->invalidateTags($tags);
516 public function onDependencyRemoval(array $dependencies) {
519 // Don't intervene if the views module is removed.
520 if (isset($dependencies['module']) && in_array('views', $dependencies['module'])) {
524 // If the base table for the View is provided by a module being removed, we
525 // delete the View because this is not something that can be fixed manually.
526 $views_data = Views::viewsData();
527 $base_table = $this->get('base_table');
528 $base_table_data = $views_data->get($base_table);
529 if (!empty($base_table_data['table']['provider']) && in_array($base_table_data['table']['provider'], $dependencies['module'])) {
533 $current_display = $this->getExecutable()->current_display;
534 $handler_types = Views::getHandlerTypes();
536 // Find all the handlers and check whether they want to do something on
537 // dependency removal.
538 foreach ($this->display as $display_id => $display_plugin_base) {
539 $this->getExecutable()->setDisplay($display_id);
540 $display = $this->getExecutable()->getDisplay();
542 foreach (array_keys($handler_types) as $handler_type) {
543 $handlers = $display->getHandlers($handler_type);
544 foreach ($handlers as $handler_id => $handler) {
545 if ($handler instanceof DependentWithRemovalPluginInterface) {
546 if ($handler->onDependencyRemoval($dependencies)) {
547 // Remove the handler and indicate we made changes.
548 unset($this->display[$display_id]['display_options'][$handler_types[$handler_type]['plural']][$handler_id]);
556 // Disable the View if we made changes.
557 // @todo https://www.drupal.org/node/2832558 Give better feedback for
560 // Force a recalculation of the dependencies if we made changes.
561 $this->getExecutable()->current_display = NULL;
562 $this->calculateDependencies();
566 $this->getExecutable()->setDisplay($current_display);