You are here

function _search_autocomplete_encode_formatted in Search Autocomplete 7.4

Same name and namespace in other branches
  1. 7.3 search_autocomplete.view_autocomplete.inc \_search_autocomplete_encode_formatted()

Encodes JSON in a pretty-printed fashion.

Only used inside the preview on the view configuration page.

Deprecated

The $option parameter in PHP 5.4.0 json_encode() deprecates this function.

See also

_search_autocomplete_json_encode()

1 call to _search_autocomplete_encode_formatted()
views-search-autocomplete-style.tpl.php in views/theme/views-search-autocomplete-style.tpl.php

File

./search_autocomplete.view_autocomplete.inc, line 104
Search Autocomplete Enables autocomplete functionality on search fields.

Code

function _search_autocomplete_encode_formatted($json, $depth = 0) {
  $base_indent = '  ';
  $eol = '<br />';
  $indent = str_repeat($base_indent, $depth);

  // This is based on the drupal_to_js() function.
  switch (gettype($json)) {
    case 'boolean':

      // Lowercase is necessary!
      return $json ? 'true' : 'false';
    case 'integer':
    case 'double':
      return $json;
    case 'resource':
    case 'string':
      $search = array(
        '"',
        chr(92),
        chr(8),
        chr(12),
        chr(13) . chr(10),
        chr(10),
        chr(13),
        chr(9),
      );
      $replace = array(
        '\\"',
        '\\',
        '\\b',
        '\\f',
        '\\n',
        '\\n',
        '\\r',
        '\\t',
      );
      $output = str_replace($search, $replace, $json);
      return '"' . check_plain($output) . '"';
    case 'array':

      // Arrays in JSON can't be associative.  If the array is empty or if it
      // has sequential whole number keys starting with 0, it's not associative
      // so we can go ahead and convert it as an array.
      if (empty($json) || array_keys($json) === range(0, count($json) - 1)) {
        $output = array();
        foreach ($json as $val) {
          $output[] = $indent . $base_indent . _search_autocomplete_encode_formatted($val, $depth + 1);
        }
        return '[' . (!empty($output) ? $eol . implode(',' . $eol, $output) . $eol . $indent : '') . ']';
      }

    // Otherwise, fall through to convert the array as an object.
    case 'object':
      $output = array();
      foreach ($json as $key => $val) {
        $output[] = $indent . $base_indent . _search_autocomplete_encode_formatted(strval($key)) . ' : ' . _search_autocomplete_encode_formatted($val, $depth + 1);
      }
      return '{' . (!empty($output) ? $eol . implode(',' . $eol, $output) . $eol . $indent : '') . '}';
    default:
      return 'null';
  }
}