Grunion_Contact_Form_Plugin::replace_tokens_with_input PHP Method

replace_tokens_with_input() public method

Replaces tokens like {city} or {City} (case insensitive) with the value of an input field of that name
public replace_tokens_with_input ( string $subject, array $field_values ) : string
$subject string
$field_values array Array with field label => field value associations
return string The filtered $subject with the tokens replaced
    function replace_tokens_with_input($subject, $field_values)
    {
        // Wrap labels into tokens (inside {})
        $wrapped_labels = array_map(array('Grunion_Contact_Form_Plugin', 'tokenize_label'), array_keys($field_values));
        // Sanitize all values
        $sanitized_values = array_map(array('Grunion_Contact_Form_Plugin', 'sanitize_value'), array_values($field_values));
        foreach ($sanitized_values as $k => $sanitized_value) {
            if (is_array($sanitized_value)) {
                $sanitized_values[$k] = implode(', ', $sanitized_value);
            }
        }
        // Search for all valid tokens (based on existing fields) and replace with the field's value
        $subject = str_ireplace($wrapped_labels, $sanitized_values, $subject);
        return $subject;
    }

Usage Example

 /**
  * @author tonykova
  * @covers Grunion_Contact_Form_Plugin::replace_tokens_with_input
  */
 public function test_token_with_curly_brackets_can_be_replaced()
 {
     $plugin = new Grunion_Contact_Form_Plugin();
     $subject = '{subject {token}}';
     $field_values = array('Subject {Token}' => 'Chicago');
     $this->assertEquals('Chicago', $plugin->replace_tokens_with_input($subject, $field_values));
 }