You are here

public function FacetsCustomLabelProcessor::build in Facets Custom Label 8

Runs before the renderable array is created.

Parameters

\Drupal\facets\FacetInterface $facet: The facet being changed.

\Drupal\facets\Result\ResultInterface[] $results: The results being changed.

Return value

\Drupal\facets\Result\ResultInterface[] The changed results.

Overrides BuildProcessorInterface::build

File

src/Plugin/facets/processor/FacetsCustomLabelProcessor.php, line 32

Class

FacetsCustomLabelProcessor
Provides a processor for FacetsCustomLabelProcessor.

Namespace

Drupal\facets_custom_label\Plugin\facets\processor

Code

public function build(FacetInterface $facet, array $results) {
  $replacementValues = $this
    ->getConfiguration()['replacement_values'];

  // TODO
  // As a possible performance upgrade, we could save the result of the
  // mapping processing as a serialized value in cache.
  // Split per line.
  $replacementValues_rows = preg_split('/\\r\\n|\\r|\\n/', $replacementValues);
  $replacementValues_keyedByRawRows = [];
  $replacementValues_keyedByValueRows = [];
  foreach ($replacementValues_rows as $row) {

    // TODO
    // This currently does not support display values which contain pipes.
    if (substr_count($row, self::SEPARATOR) < 2) {

      // Need at least three parts in the row.
      continue;
    }

    // Get the type of origin.
    $origin = mb_strstr($row, self::SEPARATOR, TRUE);
    if (mb_strlen($origin) == 0) {

      // No origin flag set. Do nothing for this row.
      continue;
    }
    $remaining = mb_substr($row, mb_strlen($origin) + mb_strlen(self::SEPARATOR));
    $originalValue = mb_strstr($remaining, self::SEPARATOR, TRUE);
    $remaining = mb_substr($remaining, mb_strlen($originalValue) + mb_strlen(self::SEPARATOR));
    $newLabel = $remaining;
    if (mb_strpos($origin, self::ORIGIN__RAW) !== FALSE) {
      $replacementValues_keyedByRawRows[$originalValue] = $newLabel;
      continue;
    }
    if (mb_strpos($origin, self::ORIGIN__DISPLAY) !== FALSE) {
      $replacementValues_keyedByValueRows[$originalValue] = $newLabel;
      continue;
    }
  }

  /* @var \Drupal\facets\Result\Result $result */
  foreach ($results as $result) {
    if (isset($replacementValues_keyedByRawRows[$result
      ->getRawValue()])) {
      $result
        ->setDisplayValue($replacementValues_keyedByRawRows[$result
        ->getRawValue()]);
      continue;
    }
    if (isset($replacementValues_keyedByValueRows[$result
      ->getDisplayValue()])) {
      $result
        ->setDisplayValue($replacementValues_keyedByValueRows[$result
        ->getDisplayValue()]);
      continue;
    }
  }
  return $results;
}