Commit adc574de authored by Markus Kalkbrenner's avatar Markus Kalkbrenner Committed by Markus Kalkbrenner
Browse files

Issue #3268558 by mkalkbrenner: Hierarchical facets show fragments of inactive...

Issue #3268558 by mkalkbrenner: Hierarchical facets show fragments of inactive branches if result items are assigned to multiple branches
parent 3034bb50
Loading
Loading
Loading
Loading
+53 −0
Original line number Diff line number Diff line
<?php

namespace Drupal\facets\Plugin\facets\processor;

use Drupal\facets\FacetInterface;
use Drupal\facets\Processor\BuildProcessorInterface;
use Drupal\facets\Processor\ProcessorPluginBase;

/**
 * Provides a processor that hides results of inactive siblings.
 *
 * @FacetsProcessor(
 *   id = "hide_inactive_siblings_processor",
 *   label = @Translation("Hide inactive siblings"),
 *   description = @Translation("In case that a result item belongs to different branches of a hierarchy it the hierarchical facet might show inactive fragments of other branches. This filter will hide these fragments. It could be combined with 'Show siblings' to only display the siblings of active items."),
 *   stages = {
 *     "build" = 10
 *   }
 * )
 */
class HideInactiveSiblingsProcessor extends ProcessorPluginBase implements BuildProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function build(FacetInterface $facet, array $results) {
    $facet_results = $facet->getResults();
    if ($facet->getUseHierarchy()) {
      $hierarchy = $facet->getHierarchyInstance();
      $active_items = $facet->getActiveItems();

      if (!$facet->getKeepHierarchyParentsActive()) {
        $parents_of_active_items = [];
        foreach ($active_items as $active_item) {
          $parents_of_active_items = array_merge($parents_of_active_items, $hierarchy->getParentIds($active_item));
        }
        $active_items = array_unique(array_merge($active_items, $parents_of_active_items));
      }

      $siblings = $hierarchy->getSiblingIds($active_items);
      $siblings_and_their_childs = array_merge($siblings, array_merge(...array_values($hierarchy->getChildIds($siblings))));

      foreach ($facet_results as $id => $result) {
        if (in_array($result->getRawValue(), $siblings_and_their_childs, FALSE) && !$result->isActive()) {
          unset($results[$id]);
        }
      }
    }

    return $results;
  }

}