Skip to content

Instantly share code, notes, and snippets.

@cahnory
Created August 31, 2012 12:52
Show Gist options
  • Save cahnory/3552327 to your computer and use it in GitHub Desktop.
Save cahnory/3552327 to your computer and use it in GitHub Desktop.
Working draft of a PHP Debug class
<?php
class Debug
{
protected $dumps = array();
static protected function getEmptyDump($type = 'log', $back = 1) {
$d = debug_backtrace();
return array(
'type' => $type,
'file' => $d[$back]['file'],
'line' => $d[$back]['line']
);
}
public function dump($var) {
$vars = func_get_args();
$dump = self::getEmptyDump();
$dump['vars'] = array();
foreach($vars as $key => $value) {
if(is_object($value) && !is_a($value, 'stdClass')) {
$value = array(
'class' => get_class($value),
'id' => spl_object_hash($value),
'attr' => get_object_vars($value)
);
}
$dump['vars'][] = $value;
}
$this->dumps[] = $dump;
}
public function warn($warning) {
$dump = self::getEmptyDump('warn');
$dump['msg'] = $warning;
$this->dumps[] = $dump;
}
public function toJs() {
$js = '';
foreach($this->dumps as $dump) {
if($dump['type'] === 'log') {
$js .= 'console.log(\'PHP:\','.json_encode((object)$dump['vars']).',\''.stripslashes($dump['file']).':'.$dump['line'].'\');';
} else {
$js .= 'console.warn(\'PHP: '.stripslashes($dump['msg']).'\');';
}
}
return $js;
}
public function toHeader() {
$hash = spl_object_hash($this);
foreach($this->dumps as $k => $dump) {
$id = $hash.'-'.$k;
if($dump['type'] === 'log') {
header('PHPrint-'.$id.'-source: ' . $dump['file'].' on line '.$dump['line']);
foreach($dump['vars'] as $i => $v) {
header('PHPrint-'.$id.'-'.$i.'-value: '. json_encode($v));
}
} else {
header('PHPrint-'.$id.'-warning: ' . $dump['msg']);
}
}
}
}
$d = new Debug;
$d->dump('test','ok');
$d->dump(array('test'));
$d->dump($d);
$d->warn('Ne pas oublier de supprimer les dumps');
$d->toHeader();
echo '<script>' . $d->toJs() . '</script>';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment