Skip to content

Instantly share code, notes, and snippets.

@felipevolpatto
Last active August 29, 2015 14:02
Show Gist options
  • Save felipevolpatto/71dd7f983fac6d0cc1b3 to your computer and use it in GitHub Desktop.
Save felipevolpatto/71dd7f983fac6d0cc1b3 to your computer and use it in GitHub Desktop.
Simples class to output PHP data to browser console
<?php
final class DebugHelper {
/**
* @param object $data
* @param string $name
* @param boolean $jsEval
* @return string
*/
public static function logConsole($data, $name = null, $jsEval = false) {
if ($data == null)
throw new \Exception('Data cannot be null');
$objDate = new \DateTime("NOW");
$objDate = (string)$objDate->format('d/m/Y h:m:s');
$isEvaled = false;
$type = ($data || gettype($data)) ? 'Type: ' . gettype($data) : '';
$name = ($name == null) ? sprintf("(%s)", $objDate) : sprintf("%s (%s)", $name, $objDate);
if ($jsEval && (is_array($data) || is_object($data))) {
$isEvaled = true;
$data = 'eval(' . preg_replace('#[\s\r\n\t\0\x0B]+#', '', json_encode($data)) . ')';
} else {
$data = json_encode($data);
}
# sanitalize
$searchArray = array("#'#", '#""#', "#''#", "#\n#", "#\r\n#");
$replaceArray = array('"', '', '', '\\n', '\\n');
$data = preg_replace($searchArray, $replaceArray, $data);
$data = ltrim(rtrim($data, '"'), '"');
$data = $isEvaled ? $data : (($data[0] === "'") ? $data : "'" . $data . "'");
$js = <<<JSCODE
<script>
if (!window.console) console = {};
console.log = console.log || function(name, data) {};
console.log('$name');
console.log('$type');
console.log($data);
console.log('\\n');
</script>
JSCODE;
echo $js;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment