You are here

public function Server::preSave in Search API 8

Acts on an entity before the presave hook is invoked.

Used before the entity is saved and before invoking the presave hook. Note that in case of translatable content entities this callback is only fired on their current translation. It is up to the developer to iterate over all translations if needed. This is different from its counterpart in the Field API, FieldItemListInterface::preSave(), which is fired on all field translations automatically. @todo Adjust existing implementations and the documentation according to https://www.drupal.org/node/2577609 to have a consistent API.

Parameters

\Drupal\Core\Entity\EntityStorageInterface $storage: The entity storage object.

Throws

\Exception When there is a problem that should prevent saving the entity.

Overrides ConfigEntityBase::preSave

See also

\Drupal\Core\Field\FieldItemListInterface::preSave()

File

src/Entity/Server.php, line 479

Class

Server
Defines the search server configuration entity.

Namespace

Drupal\search_api\Entity

Code

public function preSave(EntityStorageInterface $storage) {
  parent::preSave($storage);

  // The rest of the code only applies to updates.
  if (!isset($this->original)) {
    return;
  }

  // Retrieve active config overrides for this server.
  $overrides = Utility::getConfigOverrides($this);

  // If there are overrides for the backend or its configuration, attempt to
  // apply them for the preUpdate() call.
  if (isset($overrides['backend']) || isset($overrides['backend_config'])) {
    $backend_config = $this
      ->getBackendConfig();
    if (isset($overrides['backend_config'])) {
      $backend_config = $overrides['backend_config'];
    }
    $backend_id = $this
      ->getBackendId();
    if (isset($overrides['backend'])) {
      $backend_id = $overrides['backend'];
    }
    $backend_plugin_manager = \Drupal::service('plugin.manager.search_api.backend');
    $backend_config['#server'] = $this;
    if (!($backend = $backend_plugin_manager
      ->createInstance($backend_id, $backend_config))) {
      $label = $this
        ->label();
      throw new SearchApiException("The backend with ID '{$backend_id}' could not be retrieved for server '{$label}'.");
    }
  }
  else {
    $backend = $this
      ->getBackend();
  }
  $backend
    ->preUpdate();

  // If the server is being disabled, also disable all its indexes.
  if (!$this
    ->isSyncing() && !$this
    ->isInstallingFromExtension() && !isset($overrides['status']) && !$this
    ->status() && $this->original
    ->status()) {
    foreach ($this
      ->getIndexes([
      'status' => TRUE,
    ]) as $index) {

      /** @var \Drupal\search_api\IndexInterface $index */
      $index
        ->setStatus(FALSE)
        ->save();
    }
  }
}