function ListItemBase::extractAllowedValues

Same name in other branches
  1. 9 core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php \Drupal\options\Plugin\Field\FieldType\ListItemBase::extractAllowedValues()
  2. 8.9.x core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php \Drupal\options\Plugin\Field\FieldType\ListItemBase::extractAllowedValues()
  3. 10 core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php \Drupal\options\Plugin\Field\FieldType\ListItemBase::extractAllowedValues()

Extracts the allowed values array from the allowed_values element.

Parameters

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(array $list, bool $has_data) {
    $values = [];
    $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.