comparison core/modules/views/src/Entity/View.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children 1fec387a4317
comparison
equal deleted inserted replaced
-1:000000000000 0:4c8ae668cc8c
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\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;
15
16 /**
17 * Defines a View configuration entity class.
18 *
19 * @ConfigEntityType(
20 * id = "view",
21 * label = @Translation("View", context = "View entity type"),
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 $displays = $this->get('display');
294
295 $this->fixTableNames($displays);
296
297 // Sort the displays.
298 ksort($displays);
299 $this->set('display', ['default' => $displays['default']] + $displays);
300
301 // @todo Check whether isSyncing is needed.
302 if (!$this->isSyncing()) {
303 $this->addCacheMetadata();
304 }
305 }
306
307 /**
308 * Fixes table names for revision metadata fields of revisionable entities.
309 *
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.
314 *
315 * @param array &$displays
316 * An array containing display handlers of a view.
317 *
318 * @deprecated in Drupal 8.3.0, will be removed in Drupal 9.0.0.
319 */
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';
333
334 // Check if this is a revision metadata field and if it uses the
335 // wrong table.
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;
338 }
339 }
340 }
341 }
342 }
343 }
344 }
345
346 /**
347 * Fills in the cache metadata of this view.
348 *
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:
351 * - the max-age
352 * - the cache contexts
353 * - the cache tags
354 *
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.
358 */
359 protected function addCacheMetadata() {
360 $executable = $this->getExecutable();
361
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);
367
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]);
375 }
376 // Restore the previous active display.
377 $executable->setDisplay($current_display);
378 }
379
380 /**
381 * {@inheritdoc}
382 */
383 public function postSave(EntityStorageInterface $storage, $update = TRUE) {
384 parent::postSave($storage, $update);
385
386 // @todo Remove if views implements a view_builder controller.
387 views_invalidate_cache();
388 $this->invalidateCaches();
389
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();
393 }
394 }
395
396 /**
397 * {@inheritdoc}
398 */
399 public static function postLoad(EntityStorageInterface $storage, array &$entities) {
400 parent::postLoad($storage, $entities);
401 foreach ($entities as $entity) {
402 $entity->mergeDefaultDisplaysOptions();
403 }
404 }
405
406 /**
407 * {@inheritdoc}
408 */
409 public static function preCreate(EntityStorageInterface $storage, array &$values) {
410 parent::preCreate($storage, $values);
411
412 // If there is no information about displays available add at least the
413 // default display.
414 $values += [
415 'display' => [
416 'default' => [
417 'display_plugin' => 'default',
418 'id' => 'default',
419 'display_title' => 'Master',
420 'position' => 0,
421 'display_options' => [],
422 ],
423 ]
424 ];
425 }
426
427 /**
428 * {@inheritdoc}
429 */
430 public function postCreate(EntityStorageInterface $storage) {
431 parent::postCreate($storage);
432
433 $this->mergeDefaultDisplaysOptions();
434 }
435
436 /**
437 * {@inheritdoc}
438 */
439 public static function preDelete(EntityStorageInterface $storage, array $entities) {
440 parent::preDelete($storage, $entities);
441
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();
449 }
450 }
451 }
452
453 /**
454 * {@inheritdoc}
455 */
456 public static function postDelete(EntityStorageInterface $storage, array $entities) {
457 parent::postDelete($storage, $entities);
458
459 $tempstore = \Drupal::service('user.shared_tempstore')->get('views');
460 foreach ($entities as $entity) {
461 $tempstore->delete($entity->id());
462 }
463 }
464
465 /**
466 * {@inheritdoc}
467 */
468 public function mergeDefaultDisplaysOptions() {
469 $displays = [];
470 foreach ($this->get('display') as $key => $options) {
471 $options += [
472 'display_options' => [],
473 'display_plugin' => NULL,
474 'id' => NULL,
475 'display_title' => '',
476 'position' => NULL,
477 ];
478 // Add the defaults for the display.
479 $displays[$key] = $options;
480 }
481 $this->set('display', $displays);
482 }
483
484 /**
485 * {@inheritdoc}
486 */
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']);
493 }
494
495 /**
496 * {@inheritdoc}
497 */
498 public function __sleep() {
499 $keys = parent::__sleep();
500 unset($keys[array_search('executable', $keys)]);
501 return $keys;
502 }
503
504 /**
505 * Invalidates cache tags.
506 */
507 public function invalidateCaches() {
508 // Invalidate cache tags for cached rows.
509 $tags = $this->getCacheTags();
510 \Drupal::service('cache_tags.invalidator')->invalidateTags($tags);
511 }
512
513 /**
514 * {@inheritdoc}
515 */
516 public function onDependencyRemoval(array $dependencies) {
517 $changed = FALSE;
518
519 // Don't intervene if the views module is removed.
520 if (isset($dependencies['module']) && in_array('views', $dependencies['module'])) {
521 return FALSE;
522 }
523
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'])) {
530 return FALSE;
531 }
532
533 $current_display = $this->getExecutable()->current_display;
534 $handler_types = Views::getHandlerTypes();
535
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();
541
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]);
549 $changed = TRUE;
550 }
551 }
552 }
553 }
554 }
555
556 // Disable the View if we made changes.
557 // @todo https://www.drupal.org/node/2832558 Give better feedback for
558 // disabled config.
559 if ($changed) {
560 // Force a recalculation of the dependencies if we made changes.
561 $this->getExecutable()->current_display = NULL;
562 $this->calculateDependencies();
563 $this->disable();
564 }
565
566 $this->getExecutable()->setDisplay($current_display);
567 return $changed;
568 }
569
570 }