You are here

public function FieldsProcessorPluginBase::preIndexSave in Search API 8

Preprocesses the search index entity before it is saved.

This can, for example, be used to make sure fields needed by this processor are enabled on the index.

Overrides ProcessorPluginBase::preIndexSave

File

src/Processor/FieldsProcessorPluginBase.php, line 132

Class

FieldsProcessorPluginBase
Provides a base class for processors that work on individual fields.

Namespace

Drupal\search_api\Processor

Code

public function preIndexSave() {
  parent::preIndexSave();

  // If the "all supported fields" option is checked, we need to reset the
  // fields array and fill it with all fields defined on the index.
  if ($this->configuration['all_fields']) {
    $this->configuration['fields'] = [];
    foreach ($this->index
      ->getFields() as $field_id => $field) {
      if (!$field
        ->isHidden() && $this
        ->testType($field
        ->getType())) {
        $this->configuration['fields'][] = $field_id;
      }
    }

    // No need to explicitly check for field renames.
    return;
  }

  // Otherwise, if no fields were checked, we also have nothing to do here.
  if (empty($this->configuration['fields'])) {
    return;
  }

  // Apply field ID changes to the fields selected for this processor.
  $selected_fields = array_flip($this->configuration['fields']);
  $renames = $this->index
    ->getFieldRenames();
  $renames = array_intersect_key($renames, $selected_fields);
  if ($renames) {
    $new_fields = array_keys(array_diff_key($selected_fields, $renames));
    $new_fields = array_merge($new_fields, array_values($renames));
    $this->configuration['fields'] = $new_fields;
  }

  // Remove fields from the configuration that are no longer compatible with
  // this processor (or no longer present on the index at all).
  foreach ($this->configuration['fields'] as $i => $field_id) {
    $field = $this->index
      ->getField($field_id);
    if ($field === NULL || $field
      ->isHidden() || !$this
      ->testType($field
      ->getType())) {
      unset($this->configuration['fields'][$i]);
    }
  }

  // Serialization might be problematic if the array indices aren't completely
  // sequential.
  $this->configuration['fields'] = array_values($this->configuration['fields']);
}