You are here

function media_entity_update_8201 in Media entity 8.2

Replace Media Entity with Media.

File

./media_entity.install, line 307
Install, uninstall and update hooks for Media entity module.

Code

function media_entity_update_8201() {
  \Drupal::state()
    ->set('media_entity_core_upgrade_started', TRUE);

  // When Media is installed, it assumes that it needs to create media bundles
  // and fields. Because this is an upgrade from Media Entity, that's not the
  // case. Track existing media types and fields, so that later when we delete
  // the auto-created ones, we don't throw the baby out with the bathwater.
  $preexisting_media_config = [];
  $prefixes = [
    'core.entity_form_display.media.',
    'core.entity_view_display.media.',
    'field.field.media.',
    'field.storage.media.',
    'media.type.',
  ];
  foreach ($prefixes as $prefix) {
    foreach (\Drupal::configFactory()
      ->listAll($prefix) as $name) {
      $preexisting_media_config[] = $name;
    }
  }
  $snapshots = _media_entity_snapshot_config([
    'core.entity_view_mode.media.full',
    'core.entity_form_display.media.file.default',
    'core.entity_form_display.media.image.default',
    'core.entity_view_display.media.file.default',
    'core.entity_view_display.media.image.default',
  ], TRUE);
  $install = [
    'media',
  ];

  // Install media_entity_generic if available. It stands to reason that this
  // module will only be available if you have at least one media type that uses
  // the generic plugin, since it has been split out into its own module and is
  // only requested if there are media bundles that use it.
  // See media_entity_requirements() and
  // \Drupal\media_entity\CliService::validateDbUpdateRequirements()/
  $module_data = system_rebuild_module_data();
  if (isset($module_data['media_entity_generic'])) {
    $install[] = 'media_entity_generic';
  }

  // EXIF image handling was dropped from the patch that moved ME + MEI into
  // core. Enable "Media Entity Image EXIF" if needed, which fills in that gap.
  // See media_entity_requirements() and
  // \Drupal\media_entity\CliService::validateDbUpdateRequirements()/
  $bundles_with_exif = _media_entity_get_bundles_using_exif();
  if (!empty($bundles_with_exif) && isset($module_data['media_entity_image_exif'])) {
    $install[] = 'media_entity_image_exif';
  }

  // The module installer rebuilds container after module install. All services
  // previously instantiated could have the wrong state. Do not use any services
  // via previously assign local variables.
  \Drupal::service('module_installer')
    ->install($install);
  $config_factory = \Drupal::configFactory();
  foreach ($snapshots as $name => $data) {
    $config_factory
      ->getEditable($name)
      ->setData($data)
      ->save(TRUE);
  }
  unset($snapshots);

  // Renames the revision fields in the media_revision table and ensures that
  // overrides of these fields are also changed properly.

  /** @var \Drupal\Core\Field\FieldStorageDefinitionInterface[] $field_definitions */
  $field_definitions = \Drupal::service('entity_field.manager')
    ->getFieldStorageDefinitions('media');
  $db = Database::getConnection()
    ->schema();
  $field_renames = [
    'revision_uid' => 'revision_user',
    'revision_timestamp' => 'revision_created',
    'revision_log' => 'revision_log_message',
  ];
  $field_overrides = _media_entity_get_base_field_overrides();
  foreach ($field_renames as $old_field => $new_field) {
    $field_columns = $field_definitions[$new_field]
      ->getColumns();
    $field_property_name = $field_definitions[$new_field]
      ->getMainPropertyName();
    $db
      ->changeField('media_revision', $old_field, $new_field, $field_columns[$field_property_name]);
    if (!empty($field_overrides[$old_field])) {
      foreach ($field_overrides[$old_field] as $bundle) {
        $config_factory
          ->getEditable("core.base_field_override.media.{$bundle}.{$old_field}")
          ->set('id', "media.{$bundle}.{$new_field}")
          ->set('field_name', $new_field)
          ->save(TRUE);
        $config_factory
          ->rename("core.base_field_override.media.{$bundle}.{$old_field}", "core.base_field_override.media.{$bundle}.{$new_field}");
      }
    }
  }

  // Delete file/image media types automatically created by core media and
  // associated fields.
  foreach ($prefixes as $prefix) {
    foreach ($config_factory
      ->listAll($prefix) as $name) {
      if (!in_array($name, $preexisting_media_config)) {

        // We should only do a proper entity delete on media types if we're not
        // going to rename an existing media_entity bundle to take their place
        // later.
        if ($prefix === 'media.type.') {
          $media_entity_bundle_name = preg_replace('/^media\\.type\\./', 'media_entity.bundle.', $name);
          if (!$config_factory
            ->get($media_entity_bundle_name)
            ->isNew()) {

            // Delete the media type directly from configuration to avoid
            // triggering bundle delete hooks.
            $config_factory
              ->getEditable($name)
              ->delete();
            continue;
          }
        }
        $entity = \Drupal::service('config.manager')
          ->loadConfigEntityByName($name);

        // Check to see if the configuration entity exists. It's possible that
        // previous deletes have deleted everything.
        if ($entity) {
          $entity
            ->delete();
        }
      }
    }
  }

  // Move all module dependencies on existing config entities from
  // "media_entity" to "media".
  _media_entity_fix_dependencies('module', 'media_entity', function ($module) {
    return $module === 'media_entity' ? 'media' : $module;
  });

  // Move all module dependencies on existing config entities from
  // "media_entity_document" to "media".
  _media_entity_fix_dependencies('module', 'media_entity_document', function ($module) {
    return $module === 'media_entity_document' ? 'media' : $module;
  });

  // Move all module dependencies on existing config entities from
  // "media_entity_image" to "media".
  _media_entity_fix_dependencies('module', 'media_entity_image', function ($module) {
    return $module === 'media_entity_image' ? 'media' : $module;
  });

  // Move media_entity.settings to media.settings. Note that we don't read and
  // save in bulk because the key "icon_base" moved to "icon_base_uri".
  $config_factory
    ->getEditable('media.settings')
    ->set('icon_base_uri', $config_factory
    ->get('media_entity.settings')
    ->get('icon_base'))
    ->set('standalone_url', TRUE)
    ->save(TRUE);
  $config_factory
    ->getEditable('media_entity.settings')
    ->delete();

  // Move all bundle configs to the new plugin namespace. This means moving all
  // "media_entity.bundle.*" to "media.type.*".
  foreach ($config_factory
    ->listAll('media_entity.bundle.') as $original_name) {
    $search = '/^media_entity\\.bundle\\./';
    $replace = 'media.type.';
    $new_name = preg_replace($search, $replace, $original_name);
    $config_factory
      ->rename($original_name, $new_name);
    $config = $config_factory
      ->getEditable($new_name);
    $source_id = $config
      ->get('type');
    $config
      ->set('source_configuration', $config
      ->get('type_configuration'))
      ->clear('type_configuration')
      ->set('source', $source_id == 'document' ? 'file' : $source_id)
      ->clear('type')
      ->save();
    _media_entity_fix_dependencies('config', $original_name, function ($bundle_id) use ($search, $replace) {
      return preg_replace($search, $replace, $bundle_id);
    });

    /** @var \Drupal\media\MediaTypeInterface $media_type */
    $media_type = \Drupal::entityTypeManager()
      ->getStorage('media_type')
      ->load($config
      ->get('id'));
    $media_source = $media_type
      ->getSource();
    $source_field = $media_source
      ->getSourceFieldDefinition($media_type);
    if (!$source_field) {
      $source_field = $media_source
        ->createSourceField($media_type);
      $source_field
        ->getFieldStorageDefinition()
        ->save();
      $source_field
        ->save();
      $media_type
        ->set('source_configuration', [
        'source_field' => $source_field
          ->getName(),
      ]);
    }
    $media_type
      ->save();
  }

  // Clear the old UUID map.
  \Drupal::keyValue(QueryFactory::CONFIG_LOOKUP_PREFIX . 'media_bundle')
    ->deleteAll();

  // Update any views that use the entity:media_bundle argument validator.
  _media_entity_update_views();

  // Update media action plugins.
  $old_new_action_id_map = [
    'media_delete_action' => 'entity:delete_action:media',
    'media_publish_action' => 'entity:publish_action:media',
    'media_unpublish_action' => 'entity:unpublish_action:media',
    'media_save_action' => 'entity:save_action:media',
  ];

  /** @var \Drupal\system\Entity\Action[] $actions */
  $actions = \Drupal::entityTypeManager()
    ->getStorage('action')
    ->loadMultiple();
  foreach ($actions as $action) {
    if (isset($old_new_action_id_map[$action
      ->getPlugin()
      ->getPluginId()])) {
      $action
        ->setPlugin($old_new_action_id_map[$action
        ->getPlugin()
        ->getPluginId()]);
      $action
        ->save();
    }
  }

  /** @var \Drupal\user\Entity\Role $role */
  foreach (Role::loadMultiple() as $role) {
    if ($role
      ->hasPermission('administer media bundles')) {
      $role
        ->revokePermission('administer media bundles')
        ->grantPermission('administer media types')
        ->save();
    }
  }

  // Disable media_entity_image, media_entity_document, and media_entity. They
  // are all superseded by core Media.
  if (isset($module_data['media_entity_image'])) {
    \Drupal::service('module_installer')
      ->uninstall([
      'media_entity_image',
    ]);
  }
  if (isset($module_data['media_entity_document'])) {
    \Drupal::service('module_installer')
      ->uninstall([
      'media_entity_document',
    ]);
  }
  \Drupal::service('module_installer')
    ->uninstall([
    'media_entity',
  ]);

  // @todo This can be removed when
  //   https://www.drupal.org/project/drupal/issues/3063734 lands.
  // Remove media_entity from the update schema list.
  register_shutdown_function(function () {
    \Drupal::keyValue('system.schema')
      ->delete('media_entity');
  });
}