You are here

public function DependentFacetProcessor::build in Facets 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/DependentFacetProcessor.php, line 154

Class

DependentFacetProcessor
Provides a processor that makes a facet depend on the state of another facet.

Namespace

Drupal\facets\Plugin\facets\processor

Code

public function build(FacetInterface $facet, array $results) {
  $conditions = $this
    ->getConfiguration();
  foreach ($conditions as $facet_id => $condition) {
    if (empty($condition['enable'])) {
      continue;
    }
    $enabled_conditions[$facet_id] = $condition;
  }

  // Return as early as possible when there are no settings for allowed
  // facets.
  if (empty($enabled_conditions)) {
    return $results;
  }
  $return = TRUE;
  foreach ($enabled_conditions as $facet_id => $condition_settings) {

    /** @var \Drupal\facets\Entity\Facet $current_facet */
    $current_facet = $this->facetStorage
      ->load($facet_id);
    $current_facet = $this->facetsManager
      ->returnProcessedFacet($current_facet);
    if ($condition_settings['condition'] == 'not_empty') {
      $return = !empty($current_facet
        ->getActiveItems());
    }
    if ($condition_settings['condition'] == 'values') {
      $return = FALSE;
      $values = explode(',', $condition_settings['values']);
      foreach ($current_facet
        ->getResults() as $result) {
        $isActive = $result
          ->isActive();
        $raw_value_in_expected = in_array($result
          ->getRawValue(), $values);
        $display_value_in_expected = in_array($result
          ->getDisplayValue(), $values);
        if ($isActive && ($raw_value_in_expected || $display_value_in_expected)) {
          $return = TRUE;
        }
      }
    }
    if (!empty($condition_settings['negate'])) {
      $return = !$return;
    }
  }
  return $return ? $results : [];
}