Skip to content
Snippets Groups Projects

Make TermWeightWidgetOrderProcessor respect the full hierarchy.

1 file
+ 25
29
Compare changes
  • Side-by-side
  • Inline
@@ -2,6 +2,7 @@
namespace Drupal\facets\Plugin\facets\processor;
use Drupal\Component\Utility\Number;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\UnchangingCacheableDependencyTrait;
use Drupal\Core\Entity\EntityTypeManagerInterface;
@@ -36,6 +37,13 @@ class TermWeightWidgetOrderProcessor extends SortProcessorPluginBase implements
*/
protected $entityTypeManager;
/**
* The alpha-decimal representation of the taxonomy hierarchy in a flat array.
*
* @var array
*/
protected array $hierarchy;
/**
* Constructs a new object.
*
@@ -70,39 +78,27 @@ class TermWeightWidgetOrderProcessor extends SortProcessorPluginBase implements
* {@inheritdoc}
*/
public function sortResults(Result $a, Result $b) {
// Get the term weight once.
if ($a->get('termWeight') === NULL || $b->get('termWeight') === NULL) {
$ids = [];
if ($a->get('termWeight') === NULL) {
$a_raw = $a->getRawValue();
$ids[] = $a_raw;
/** @var \Drupal\taxonomy\TermStorageInterface $term_storage */
$term_storage = $this->entityTypeManager->getStorage('taxonomy_term');
foreach ([$a->getRawValue(), $b->getRawValue()] as $term_id) {
if (isset($this->hierarchy[$term_id])) {
continue;
}
if ($b->get('termWeight') === NULL) {
$b_raw = $b->getRawValue();
$ids[] = $b_raw;
}
$entities = $this->entityTypeManager
->getStorage('taxonomy_term')
->loadMultiple($ids);
if ($a->get('termWeight') === NULL) {
if (empty($entities[$a_raw])) {
return 0;
}
$a->set('termWeight', $entities[$a_raw]->getWeight());
}
if ($b->get('termWeight') === NULL) {
if (empty($entities[$b_raw])) {
return 0;
}
$b->set('termWeight', $entities[$b_raw]->getWeight());
// Ancestors include the term itself.
$ancestors = $term_storage->loadAllParents($term_id);
// Reverse the order of the ancestors so that the root term is first.
$ancestors = \array_reverse($ancestors);
$materialised_weight = '';
foreach ($ancestors as $ancestor) {
// Build an alpha-decimal representation of the term's weight,
// which also considers the taxonomy hierarchy.
$materialised_weight .= '.' . Number::intToAlphadecimal($ancestor->getWeight());
$this->hierarchy[$ancestor->id()] = ltrim($materialised_weight, '.');
}
}
// Return the sort value.
if ($a->get('termWeight') === $b->get('termWeight')) {
return 0;
}
return ($a->get('termWeight') < $b->get('termWeight')) ? -1 : 1;
return $this->hierarchy[$a->getRawValue()] <=> $this->hierarchy[$b->getRawValue()];
}
/**
Loading