You are here

private function StrawSelection::getSelectableTerms in Super Term Reference Autocomplete Widget 8

Gets the potentially selectable terms for a given bundle.

Parameters

string $bundle_name: Vocabulary ID to retrieve terms for.

Return value

array The searchable data.

1 call to StrawSelection::getSelectableTerms()
StrawSelection::getReferenceableEntities in src/Plugin/EntityReferenceSelection/StrawSelection.php
Gets the list of referenceable entities.

File

src/Plugin/EntityReferenceSelection/StrawSelection.php, line 71

Class

StrawSelection
Provides specific access control for the taxonomy_term entity type.

Namespace

Drupal\straw\Plugin\EntityReferenceSelection

Code

private function getSelectableTerms($bundle_name) {
  $cache_context_keys = \Drupal::service('cache_contexts_manager')
    ->convertTokensToKeys([
    'user.permissions',
  ])
    ->getKeys();
  $cid = $bundle_name . ':' . implode(':', $cache_context_keys);
  $straw_cache = \Drupal::cache('straw');

  // Load from cache if possible rather than rebuilding the term list.
  if ($cached_data = $straw_cache
    ->get($cid)) {
    return $cached_data->data;
  }
  $all_terms = $this->entityTypeManager
    ->getStorage('taxonomy_term')
    ->loadTree($bundle_name);

  // We want $terms to be keyed by ID rather than numerically.
  $all_terms = array_reduce($all_terms, function ($carry, $item) {
    $carry[$item->tid] = $item;
    return $carry;
  }, []);
  $searchable_data = [];
  foreach ($all_terms as $term) {

    // Build the tree path for the term, including the names of its
    // ancestors. Currently, a single term being in multiple places in the
    // hierarchy is not actively supported (only one possible tree path can
    // get shown in the autocomplete results)
    $tree_path = $term->name;
    $current = $term;
    while (($parent_id = $current->parents[0]) && ($parent = $all_terms[$parent_id])) {
      $tree_path = $parent->name . ' >> ' . $tree_path;
      $current = $parent;
    }
    $searchable_data[] = [
      'tid' => $term->tid,
      'tree_path' => $tree_path,
    ];
  }

  // Save into cache for faster loading in the future.
  \Drupal::cache('straw')
    ->set($cid, $searchable_data, Cache::PERMANENT, [
    'taxonomy_term_list',
  ]);
  return $searchable_data;
}