function ListItemBase::extractAllowedValues

Extracts the allowed values array from the allowed_values element.

Parameters

string|array $list: The raw string or array to extract values from.

bool $has_data: The current field already has data inserted or not.

Return value

array|null The array of extracted key/value pairs, or NULL if the string is invalid.

See also

\Drupal\options\Plugin\Field\FieldType\ListItemBase::allowedValuesString()

2 calls to ListItemBase::extractAllowedValues()
ListFloatItem::extractAllowedValues in core/modules/options/src/Plugin/Field/FieldType/ListFloatItem.php
Extracts the allowed values array from the allowed_values element.
ListItemBase::validateAllowedValues in core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php
#element_validate callback for options field allowed values.
1 method overrides ListItemBase::extractAllowedValues()
ListFloatItem::extractAllowedValues in core/modules/options/src/Plugin/Field/FieldType/ListFloatItem.php
Extracts the allowed values array from the allowed_values element.

File

core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php, line 402

Class

ListItemBase
Plugin base class inherited by the options field types.

Namespace

Drupal\options\Plugin\Field\FieldType

Code

protected static function extractAllowedValues($list, $has_data) {
  $values = [];
  if (is_string($list)) {
    trigger_error('Passing a string to ' . __METHOD__ . '() is deprecated in drupal:10.2.0 and will cause an error from drupal:11.0.0. Use an array instead. See https://www.drupal.org/node/3376368', E_USER_DEPRECATED);
    $list = explode("\n", $list);
    $list = array_map('trim', $list);
    $list = array_filter($list, 'strlen');
  }
  $generated_keys = $explicit_keys = FALSE;
  foreach ($list as $position => $text) {
    // Check for an explicit key.
    $matches = [];
    if (preg_match('/(.*)\\|(.*)/', $text, $matches)) {
      // Trim key and value to avoid unwanted spaces issues.
      $key = trim($matches[1]);
      $value = trim($matches[2]);
      $explicit_keys = TRUE;
    }
    elseif (!static::validateAllowedValue($text)) {
      $key = $value = $text;
      $explicit_keys = TRUE;
    }
    elseif (!$has_data) {
      $key = (string) $position;
      $value = $text;
      $generated_keys = TRUE;
    }
    else {
      return;
    }
    $values[$key] = $value;
  }
  // We generate keys only if the list contains no explicit key at all.
  if ($explicit_keys && $generated_keys) {
    return;
  }
  return $values;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.