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\EntityStorageInterface;
9 use Drupal\Core\Language\LanguageInterface;
10 use Drupal\views\Views;
11 use Drupal\views\ViewEntityInterface;
14 * Defines a View configuration entity class.
18 * label = @Translation("View", context = "View entity type"),
20 * "access" = "Drupal\views\ViewAccessControlHandler"
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 // Sort the displays.
294 $display = $this->get('display');
296 $this->set('display', ['default' => $display['default']] + $display);
298 // @todo Check whether isSyncing is needed.
299 if (!$this->isSyncing()) {
300 $this->addCacheMetadata();
305 * Fills in the cache metadata of this view.
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:
310 * - the cache contexts
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.
317 protected function addCacheMetadata() {
318 $executable = $this->getExecutable();
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);
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]);
334 // Restore the previous active display.
335 $executable->setDisplay($current_display);
341 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
342 parent::postSave($storage, $update);
344 // @todo Remove if views implements a view_builder controller.
345 views_invalidate_cache();
346 $this->invalidateCaches();
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();
357 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
358 parent::postLoad($storage, $entities);
359 foreach ($entities as $entity) {
360 $entity->mergeDefaultDisplaysOptions();
367 public static function preCreate(EntityStorageInterface $storage, array &$values) {
368 parent::preCreate($storage, $values);
370 // If there is no information about displays available add at least the
375 'display_plugin' => 'default',
377 'display_title' => 'Master',
379 'display_options' => [],
388 public function postCreate(EntityStorageInterface $storage) {
389 parent::postCreate($storage);
391 $this->mergeDefaultDisplaysOptions();
397 public static function preDelete(EntityStorageInterface $storage, array $entities) {
398 parent::preDelete($storage, $entities);
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();
414 public static function postDelete(EntityStorageInterface $storage, array $entities) {
415 parent::postDelete($storage, $entities);
417 $tempstore = \Drupal::service('user.shared_tempstore')->get('views');
418 foreach ($entities as $entity) {
419 $tempstore->delete($entity->id());
426 public function mergeDefaultDisplaysOptions() {
428 foreach ($this->get('display') as $key => $options) {
430 'display_options' => [],
431 'display_plugin' => NULL,
433 'display_title' => '',
436 // Add the defaults for the display.
437 $displays[$key] = $options;
439 $this->set('display', $displays);
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']);
456 public function __sleep() {
457 $keys = parent::__sleep();
458 unset($keys[array_search('executable', $keys)]);
463 * Invalidates cache tags.
465 public function invalidateCaches() {
466 // Invalidate cache tags for cached rows.
467 $tags = $this->getCacheTags();
468 \Drupal::service('cache_tags.invalidator')->invalidateTags($tags);