views.post_update.php 11.6 KB
Newer Older
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Post update functions for Views.
 */

8
use Drupal\Core\StringTranslation\TranslatableMarkup;
9
use Drupal\views\Entity\View;
10 11
use Drupal\views\Plugin\views\filter\NumericFilter;
use Drupal\views\Plugin\views\filter\StringFilter;
12 13
use Drupal\views\Views;

14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/**
 * Update the cacheability metadata for all views.
 */
function views_post_update_update_cacheability_metadata() {
  // Load all views.
  $views = \Drupal::entityManager()->getStorage('view')->loadMultiple();

  /* @var \Drupal\views\Entity\View[] $views */
  foreach ($views as $view) {
    $displays = $view->get('display');
    foreach (array_keys($displays) as $display_id) {
      $display =& $view->getDisplay($display_id);
      // Unset the cache_metadata key, so all cacheability metadata for the
      // display is recalculated.
      unset($display['cache_metadata']);
    }
    $view->save();
  }

}

35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
/**
 * Update some views fields that were previously duplicated.
 */
function views_post_update_cleanup_duplicate_views_data() {
  $config_factory = \Drupal::configFactory();
  $ids = [];
  $message = NULL;
  $data_tables = [];
  $base_tables = [];
  $revision_tables = [];
  $entities_by_table = [];
  $duplicate_fields = [];
  $handler_types = Views::getHandlerTypes();

  /** @var \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager */
  $entity_type_manager = \Drupal::service('entity_type.manager');
  // This will allow us to create an index of all entity types of the site.
  foreach ($entity_type_manager->getDefinitions() as $entity_type_id => $entity_type) {
    // Store the entity keyed by base table. If it has a data table, use that as
    // well.
    if ($data_table = $entity_type->getDataTable()) {
      $entities_by_table[$data_table] = $entity_type;
    }
    if ($base_table = $entity_type->getBaseTable()) {
      $entities_by_table[$base_table] = $entity_type;
    }

    // The following code basically contains the same kind of logic as
    // \Drupal\Core\Entity\Sql\SqlContentEntityStorage::initTableLayout() to
    // prefetch all tables (base, data, revision, and revision data).
    $base_tables[$entity_type_id] = $entity_type->getBaseTable() ?: $entity_type->id();
    $revisionable = $entity_type->isRevisionable();

    $revision_table = '';
    if ($revisionable) {
      $revision_table = $entity_type->getRevisionTable() ?: $entity_type->id() . '_revision';
    }
    $revision_tables[$entity_type_id] = $revision_table;

    $translatable = $entity_type->isTranslatable();
    $data_table = '';
    // For example the data table just exists, when the entity type is
    // translatable.
    if ($translatable) {
      $data_table = $entity_type->getDataTable() ?: $entity_type->id() . '_field_data';
    }
    $data_tables[$entity_type_id] = $data_table;

    $duplicate_fields[$entity_type_id] = array_intersect_key($entity_type->getKeys(), array_flip(['id', 'revision', 'bundle']));
  }

  foreach ($config_factory->listAll('views.view.') as $view_config_name) {
    $changed = FALSE;
    $view = $config_factory->getEditable($view_config_name);

    $displays = $view->get('display');
    if (isset($entities_by_table[$view->get('base_table')])) {
      $entity_type = $entities_by_table[$view->get('base_table')];
      $entity_type_id = $entity_type->id();
      $data_table = $data_tables[$entity_type_id];
      $base_table = $base_tables[$entity_type_id];
      $revision_table = $revision_tables[$entity_type_id];

      if ($data_table) {
        foreach ($displays as $display_name => &$display) {
          foreach ($handler_types as $handler_type) {
            if (!empty($display['display_options'][$handler_type['plural']])) {
              foreach ($display['display_options'][$handler_type['plural']] as $field_name => &$field) {
                $table = $field['table'];
                if (($table === $base_table || $table === $revision_table) && in_array($field_name, $duplicate_fields[$entity_type_id])) {
                  $field['table'] = $data_table;
                  $changed = TRUE;
                }
              }
            }
          }
        }
      }
    }

    if ($changed) {
      $view->set('display', $displays);
      $view->save();
      $ids[] = $view->get('id');
    }
  }
  if (!empty($ids)) {
    $message = new TranslatableMarkup('Updated tables for field handlers for views: @ids', ['@ids' => implode(', ', array_unique($ids))]);
  }

  return $message;
}

128 129 130 131 132
/**
 * Include field formatter dependencies in a view when the formatter is used.
 */
function views_post_update_field_formatter_dependencies() {
  $views = View::loadMultiple();
133
  array_walk($views, function (View $view) {
134 135 136 137
    $view->save();
  });
}

138 139 140 141 142
/**
 * Fix views with dependencies on taxonomy terms that don't exist.
 */
function views_post_update_taxonomy_index_tid() {
  $views = View::loadMultiple();
143
  array_walk($views, function (View $view) {
144 145 146 147 148 149 150 151
    $old_dependencies = $view->getDependencies();
    $new_dependencies = $view->calculateDependencies()->getDependencies();
    if ($old_dependencies !== $new_dependencies) {
      $view->save();
    }
  });
}

152 153 154 155 156
/**
 * Fix views with serializer dependencies.
 */
function views_post_update_serializer_dependencies() {
  $views = View::loadMultiple();
157
  array_walk($views, function (View $view) {
158 159 160 161 162 163 164 165
    $old_dependencies = $view->getDependencies();
    $new_dependencies = $view->calculateDependencies()->getDependencies();
    if ($old_dependencies !== $new_dependencies) {
      $view->save();
    }
  });
}

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
/**
 * Set all boolean filter values to strings.
 */
function views_post_update_boolean_filter_values() {
  $config_factory = \Drupal::configFactory();
  foreach ($config_factory->listAll('views.view.') as $view_config_name) {
    $view = $config_factory->getEditable($view_config_name);
    $save = FALSE;
    foreach ($view->get('display') as $display_name => $display) {
      if (isset($display['display_options']['filters'])) {
        foreach ($display['display_options']['filters'] as $filter_name => $filter) {
          if (isset($filter['plugin_id']) && $filter['plugin_id'] === 'boolean') {
            $new_value = FALSE;
            // Update all boolean and integer values to strings.
            if ($filter['value'] === TRUE || $filter['value'] === 1) {
              $new_value = '1';
            }
            elseif ($filter['value'] === FALSE || $filter['value'] === 0) {
              $new_value = '0';
            }
            if ($new_value !== FALSE) {
              $view->set("display.$display_name.display_options.filters.$filter_name.value", $new_value);
              $save = TRUE;
            }
          }
        }
      }
    }
    if ($save) {
      $view->save();
    }
  }
}

200 201 202 203 204 205 206
/**
 * Rebuild caches to ensure schema changes are read in.
 */
function views_post_update_grouped_filters() {
  // Empty update to cause a cache rebuild so that the schema changes are read.
}

207 208 209 210 211 212 213
/**
 * Fix table names for revision metadata fields.
 */
function views_post_update_revision_metadata_fields() {
  // The table names are fixed automatically in
  // \Drupal\views\Entity\View::preSave(), so we just need to re-save all views.
  $views = View::loadMultiple();
214
  array_walk($views, function (View $view) {
215 216 217
    $view->save();
  });
}
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260

/**
 * Add additional settings to the entity link field and convert node_path usage
 * to entity_link.
 */
function views_post_update_entity_link_url() {
  // Load all views.
  $views = \Drupal::entityTypeManager()->getStorage('view')->loadMultiple();

  /* @var \Drupal\views\Entity\View[] $views */
  foreach ($views as $view) {
    $displays = $view->get('display');
    $changed = FALSE;
    foreach ($displays as $display_name => &$display) {
      if (isset($display['display_options']['fields'])) {
        foreach ($display['display_options']['fields'] as $field_name => &$field) {
          if (isset($field['plugin_id']) && $field['plugin_id'] === 'entity_link') {
            // Add any missing settings for entity_link.
            if (!isset($field['output_url_as_text'])) {
              $field['output_url_as_text'] = FALSE;
              $changed = TRUE;
            }
            if (!isset($field['absolute'])) {
              $field['absolute'] = FALSE;
              $changed = TRUE;
            }
          }
          elseif (isset($field['plugin_id']) && $field['plugin_id'] === 'node_path') {
            // Convert the use of node_path to entity_link.
            $field['plugin_id'] = 'entity_link';
            $field['field'] = 'view_node';
            $field['output_url_as_text'] = TRUE;
            $changed = TRUE;
          }
        }
      }
    }
    if ($changed) {
      $view->set('display', $displays);
      $view->save();
    }
  }
}
261 262 263 264 265 266 267 268 269 270 271 272 273 274

/**
 * Update dependencies for moved bulk field plugin.
 */
function views_post_update_bulk_field_moved() {
  $views = View::loadMultiple();
  array_walk($views, function (View $view) {
    $old_dependencies = $view->getDependencies();
    $new_dependencies = $view->calculateDependencies()->getDependencies();
    if ($old_dependencies !== $new_dependencies) {
      $view->save();
    }
  });
}
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293

/**
 * Add placeholder settings to string or numeric filters.
 */
function views_post_update_filter_placeholder_text() {
  // Load all views.
  $views = \Drupal::entityTypeManager()->getStorage('view')->loadMultiple();
  /** @var \Drupal\views\Plugin\ViewsHandlerManager $filter_manager */
  $filter_manager = \Drupal::service('plugin.manager.views.filter');

  /* @var \Drupal\views\Entity\View[] $views */
  foreach ($views as $view) {
    $displays = $view->get('display');
    $save = FALSE;
    foreach ($displays as $display_name => &$display) {
      if (isset($display['display_options']['filters'])) {
        foreach ($display['display_options']['filters'] as $filter_name => &$filter) {
          // Any of the children of the modified classes will also be inheriting
          // the new settings.
294
          $filter_instance = $filter_manager->getHandler($filter);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
          if ($filter_instance instanceof StringFilter) {
            if (!isset($filter['expose']['placeholder'])) {
              $filter['expose']['placeholder'] = '';
              $save = TRUE;
            }
          }
          elseif ($filter_instance instanceof NumericFilter) {
            if (!isset($filter['expose']['placeholder'])) {
              $filter['expose']['placeholder'] = '';
              $save = TRUE;
            }
            if (!isset($filter['expose']['min_placeholder'])) {
              $filter['expose']['min_placeholder'] = '';
              $save = TRUE;
            }
            if (!isset($filter['expose']['max_placeholder'])) {
              $filter['expose']['max_placeholder'] = '';
              $save = TRUE;
            }
          }
        }
      }
    }
    if ($save) {
      $view->set('display', $displays);
      $view->save();
    }
  }
}
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348

/**
 * Fix cache max age for table displays.
 */
function views_post_update_table_display_cache_max_age(&$sandbox = NULL) {
  $storage = \Drupal::entityTypeManager()->getStorage('view');
  if (!isset($sandbox['views'])) {
    $sandbox['views'] = $storage->getQuery()->accessCheck(FALSE)->execute();
    $sandbox['count'] = count($sandbox['views']);
  }

  for ($i = 0; $i < 10 && count($sandbox['views']); $i++) {
    $view_id = array_shift($sandbox['views']);
    if ($view = $storage->load($view_id)) {
      $displays = $view->get('display');
      foreach ($displays as $display_name => &$display) {
        if (isset($display['display_options']['style']['type']) && $display['display_options']['style']['type'] === 'table') {
          $view->save();
        }
      }
    }
  }

  $sandbox['#finished'] = empty($sandbox['views']) ? 1 : ($sandbox['count'] - count($sandbox['views'])) / $sandbox['count'];
}