You are here

private function CshsOptionsFromHelper::getOptions in Client-side Hierarchical Select 8

Same name and namespace in other branches
  1. 8.3 src/CshsOptionsFromHelper.php \Drupal\cshs\CshsOptionsFromHelper::getOptions()
  2. 8.2 src/CshsOptionsFromHelper.php \Drupal\cshs\CshsOptionsFromHelper::getOptions()

Collects the options.

Parameters

string $vocabulary_id: Name of taxonomy vocabulary.

int $parent: ID of a parent term.

int|string $none_value: Value for the first option.

int|null $max_depth: The number of levels of the tree to return.

Return value

array[] Widget options.

2 calls to CshsOptionsFromHelper::getOptions()
CshsOptionsFromHelper::formElement in src/CshsOptionsFromHelper.php
Returns the form for a single widget.
CshsOptionsFromHelper::settingsForm in src/CshsOptionsFromHelper.php
Returns a form to configure settings.

File

src/CshsOptionsFromHelper.php, line 292

Class

CshsOptionsFromHelper
Defines a class for getting options for a cshs form element from vocabulary.

Namespace

Drupal\cshs

Code

private function getOptions(string $vocabulary_id, int $parent = 0, $none_value = 0, int $max_depth = NULL) : array {
  \assert(\is_int($none_value) || \is_string($none_value));
  static $cache = [];
  $cache_id = "{$vocabulary_id}:{$parent}:{$none_value}:{$max_depth}";
  if (!isset($cache[$cache_id])) {
    $storage = $this
      ->getTermStorage();
    $cache[$cache_id] = [
      $none_value => [
        // phpcs:ignore Drupal.Semantics.FunctionT.NotLiteralString
        'name' => $this
          ->t(CshsElement::NONE_LABEL),
        'parent_tid' => 0,
      ],
    ];
    if ($this
      ->needsTranslatedContent()) {
      $get_name = function (\stdClass $term) use ($storage) : string {
        return $this
          ->getTranslationFromContext($storage
          ->load($term->tid))
          ->label();
      };
    }
    else {

      // Avoid loading the entity if we don't need its specific translation.
      $get_name = static function (\stdClass $term) : string {
        return $term->name;
      };
    }
    foreach ($storage
      ->loadTree($vocabulary_id, $parent, $max_depth, FALSE) as $term) {
      \assert($term instanceof \stdClass);
      \assert(\is_array($term->parents));
      \assert(\is_numeric($term->status));
      \assert(\is_numeric($term->depth));
      \assert(\is_numeric($term->tid));
      \assert(\is_string($term->name));

      // Allow only published terms.
      if ((bool) $term->status) {
        $parents = \array_values($term->parents);
        $cache[$cache_id][$term->tid] = [
          'name' => \str_repeat('- ', $term->depth) . $get_name($term),
          'parent_tid' => (int) \reset($parents),
        ];
      }
    }
  }
  return $cache[$cache_id];
}