2009-04-23

function debug_writeflnh()

/// write sprint-formatted, html-encoded string to STDOUT
/// return INT(0...) number of parsed values (format string not included) | FALSE
function debug_writeflnh() {
  @list($dbbt, $caller) = debug_backtrace();
  if (isset($caller)) {
    $caller = isset($caller['class'])
        ? ($caller['class'] . (isset($caller['type']) ? $caller['type'] : ':::') . $caller['function'])
        : $caller['function'];
  }
  else {
    $caller = '___MAIN';
  }

  echo '<em class="fw-debug">', $caller, '(', $dbbt['line'], '):</em> ';

  $args = & $dbbt['args'];
  $num_args = count($args);
  if (0 === $num_args) {
    echo '<br />', CRLF, CRLF;
    return 0;
  }

  if (1 === $num_args) {
    $format = '%s';
    $first_arg = 0;
  }
  else {
    $format = & $args[0];
    $first_arg = 1;
  }

  if (!is_string($format)) {
    return FALSE;
  }

  // array_key_exists() catches $arg => NULL, which isset() doesn't
  for (
      $pos = 0, $arg = $first_arg;
      (isset($args[$arg]) || array_key_exists($arg, $args)) &&
      preg_match(
          '/([^%]*)(%(?:[0\x20]|\'[^\'])?-?[0-9]*(?:(?:\.[0-9])?f|[bcduosxX]))/S',
          $format, $hits, PREG_OFFSET_CAPTURE, $pos
      );
      $pos = $hits[2][1] + strlen($hits[2][0]), ++$arg
  ) {
    // from format string
    if (isset($hits[1][0][0])) { // !empty()
      echo htmlspecialchars($hits[1][0]);
    }
    // format string template
    if (1 === strpos($hits[2][0], 's')) { // 's' === $hits[2][0][1]
      // a "compound" type is a non-scalar type
      if ($is_compound = (is_array($args[$arg]) || is_object($args[$arg]))) {
        echo CRLF,'<pre class="fw-debug">';
      }
      ob_start();
      //debug_zval_dump($args[$arg]); // shows number of linked references
      var_dump($args[$arg]);

      static $pcre = '/\]=>(\r\n|[\r\n])(\x20\x20)+/S';
      static $prpl = '] => ';
      echo htmlspecialchars(preg_replace($pcre, $prpl, ob_get_clean()));
      if ($is_compound) {
        echo '</pre>', CRLF;
      }
    }
    else {
      echo htmlspecialchars(sprintf($hits[2][0], $args[$arg]));
    }
  }

  if ($pos < strlen($format)) {
    echo htmlspecialchars(substr($format, $pos));
  }
  echo '<br />', CRLF, CRLF;

  // return number of processed argument variables
  return $num_args - $first_arg;
}