You are here

public function NameOptionsProvider::getOptions in Name Field 8

Options for a name component.

File

src/NameOptionsProvider.php, line 70

Class

NameOptionsProvider
The name option provider for the name field.

Namespace

Drupal\name

Code

public function getOptions(FieldDefinitionInterface $field, $component) {
  $fs = $field
    ->getSettings();
  $options = $fs[$component . '_options'];
  foreach ($options as $index => $opt) {
    if (preg_match(self::vocabularyRegExp, trim($opt), $matches)) {
      unset($options[$index]);
      if ($this->termStorage && $this->vocabularyStorage) {
        $vocabulary = $this->vocabularyStorage
          ->load($matches[1]);
        if ($vocabulary) {
          $max_length = isset($fs['max_length'][$component]) ? $fs['max_length'][$component] : 255;
          foreach ($this->termStorage
            ->loadTree($vocabulary
            ->id()) as $term) {
            if (mb_strlen($term->name) <= $max_length) {
              $options[] = $term->name;
            }
          }
        }
      }
    }
  }

  // Options could come from multiple sources, filter duplicates.
  $options = array_unique($options);
  if (isset($fs['sort_options']) && !empty($fs['sort_options'][$component])) {
    natcasesort($options);
  }
  $default = FALSE;
  foreach ($options as $index => $opt) {
    if (strpos($opt, '--') === 0) {
      unset($options[$index]);
      $default = trim(mb_substr($opt, 2));
    }
  }
  $options = array_map('trim', $options);
  $options = array_combine($options, $options);
  if ($default !== FALSE) {
    $options = [
      '' => $default,
    ] + $options;
  }
  return $options;
}