You are here

function _form_options_from_text in Options Element 6

Same name and namespace in other branches
  1. 7 options_element.inc \_form_options_from_text()

Logic function for form_options_from_text(). Do not call directly.

See also

form_options_from_text()

1 call to _form_options_from_text()
form_options_from_text in ./options_element.module
Create an array representation of text option values.

File

./options_element.inc, line 350
All logic for options_element form elements.

Code

function _form_options_from_text($text, $key_type, $flat = FALSE, &$duplicates = array()) {
  $keys = array();
  $items = array();
  $rows = array_filter(explode("\n", trim($text)), 'strlen');
  $group = FALSE;
  foreach ($rows as $row) {
    $row = trim($row);
    $matches = array();

    // Check for a simple empty row.
    if (!strlen($row)) {
      continue;
    }
    elseif (!$flat && preg_match('/^\\<((([^>|]*)\\|)?([^>]*))\\>$/', $row, $matches)) {
      if ($matches[1] === '') {
        $group = FALSE;
      }
      else {
        $group = $matches[4] ? $matches[4] : '';
        $keys[] = $group;
      }
    }
    elseif (($key_type == 'mixed' || $key_type == 'custom' || $key_type == 'numeric') && preg_match('/^([^|]+)\\|(.*)$/', $row, $matches)) {
      $key = $matches[1];
      $value = $matches[2];
      $keys[] = $key;
      $items[] = array(
        'key' => $key,
        'value' => $value,
        'group' => $group,
      );
    }
    else {
      $items[] = array(
        'key' => NULL,
        'value' => $row,
        'group' => $group,
      );
    }
  }

  // Expand the list into a nested array, assign keys and check duplicates.
  $options = array();
  $new_key = 1;
  foreach ($items as $item) {
    $int_key = $item['key'] * 1;
    if (is_int($int_key)) {
      $new_key = max($int_key, $new_key);
    }
  }
  foreach ($items as $item) {

    // Assign a key if needed.
    if ($key_type == 'none') {
      $item['key'] = $new_key++;
    }
    elseif (!isset($item['key'])) {
      while (in_array($new_key, $keys)) {
        $new_key++;
      }
      $keys[] = $new_key;
      $item['key'] = $new_key;
    }
    if ($item['group']) {
      if (isset($options[$item['group']][$item['key']])) {
        $duplicates[] = $item['key'];
      }
      $options[$item['group']][$item['key']] = $item['value'];
    }
    else {
      if (isset($options[$item['key']])) {
        $duplicates[] = $item['key'];
      }
      $options[$item['key']] = $item['value'];
    }
  }
  return $options;
}