function chado_replace_tokens

3.x tripal_chado.api.inc chado_replace_tokens($string, $record)

Replace all Chado Tokens in a given string.

NOTE: If there is no value for a token then the token is removed.

Parameters

string $string: The string containing tokens.

$record: A Chado record as generated by chado_generate_var()

Return value

The string will all tokens replaced with values.

Related topics

2 calls to chado_replace_tokens()
obi__organism::load in tripal_chado/includes/TripalFields/obi__organism/obi__organism.inc
tripal_replace_chado_tokens in tripal_chado/api/tripal_chado.DEPRECATED.api.inc
Replace all Chado Tokens in a given string.

File

tripal_chado/api/tripal_chado.api.inc, line 334
This file contains miscellaneous API functions specific to working with records in Chado that do not have a home in any other sub category of API functions.

Code

function chado_replace_tokens($string, $record) {
  // Get the list of tokens
  $tokens = chado_get_tokens($record->tablename);

  // Determine which tokens were used in the format string
  if (preg_match_all('/\[[^]]+\]/', $string, $used_tokens)) {
    // Get the value for each token used
    foreach ($used_tokens[0] as $token) {
      $token_info = $tokens[$token];
      if (!empty($token_info)) {
        $table = $token_info['table'];
        $var = $record;
        $value = '';

        // Iterate through each portion of the location string. An example string
        // might be:  stock > type_id > name.
        $location = explode('>', $token_info['location']);
        foreach ($location as $index) {
          $index = trim($index);

          // if $var is an object then it is the $node object or a table
          // that has been expanded.
          if (is_object($var)) {
            // check to see if the index is a member of the object. If so,
            // then reset the $var to this value.
            if (property_exists($var, $index)) {
              $value = $var->$index;
            }
          }
          // if the $var is an array then there are multiple instances of the same
          // table in a FK relationship (e.g. relationship tables)
          elseif (is_array($var)) {
            $value = $var[$index];
          }
          else {
            tripal_report_error('tripal_chado', TRIPAL_WARNING, 
            'Tokens: Unable to determine the value of %token. Things went awry when trying ' .
              'to access \'%index\' for the following: \'%var\'.', 
            array('%token' => $token, '%index' => $index, '%var' => print_r($var, TRUE))
            );
          }
        }
        $string = str_replace($token, $value, $string);
      }
    }
  }
  return $string;
}