Skip to content

Instantly share code, notes, and snippets.

@1pxsun
Last active July 27, 2016 14:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1pxsun/5d86dcf24172f904de14 to your computer and use it in GitHub Desktop.
Save 1pxsun/5d86dcf24172f904de14 to your computer and use it in GitHub Desktop.
New simplified version of Console for PHP. `composer require 1pxsun/console`
{
"name": "1pxsun/console",
"autoload": {
"files": [
"console.php",
"wordpress-console.php"
]
}
}
<?php
class console {
const VERSION = "0.5.2";
static $instance, $debug, $error, $output, $logs, $timers;
static function enable($debug = true) {
self::$debug = ($debug === null) ? in_array($_SERVER["REMOTE_ADDR"], ["127.0.0.1", "::1"]) : $debug;
error_reporting(-1);
@ini_set("display_errors", false);
ob_start(function($s) {
self::$error && !headers_sent() && http_response_code(500);
return self::$error ? "<code>Server Error</code>" . self::$output : $s;
});
register_shutdown_function(function() {
$e = error_get_last();
$toHtml = empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& empty($_SERVER['HTTP_X_PHPCONSOLE']) && PHP_SAPI !== 'cli'
&& !preg_match('#^Content-Type: (?!text/html)#im', implode("\n", headers_list()));
if ($e && in_array($e['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) {
self::exception(new ErrorException($e['message'], 0, $e['type'], $e['file'], $e['line']), true);
}
if (self::$debug) {
$title = sprintf("%s %s %.1fMB %.1fms", $_SERVER["REQUEST_METHOD"], $_SERVER["REQUEST_URI"],
memory_get_peak_usage() / 1024 / 1024,
(microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]) * 1000
);
$collapsed = $toHtml || self::$error ? "" : "Collapsed";
self::$logs = sprintf("console.group%s&&eval('console.group%s('+%s+')//# sourceURL=Console_%s,_PHP_%d.%d');%s;console.groupEnd&&console.groupEnd();",
$collapsed, $collapsed, json_encode(json_encode($title)), self::VERSION, PHP_MAJOR_VERSION, PHP_MINOR_VERSION, self::$logs
);
if ($toHtml) {
self::$logs .= "!function(x,p,e,s,o,c){if(x[e])return;else{x[e]=1}c=function(u,a){a=document.createElement('a');a.href=u;return a.origin===window.location.origin};x.phpConsoleEnabled=1;s=x[p].send;x[p].send=function(){var _=this.onload;this.onload=function(){if(c(this.responseURL))eval(eval(this.getResponseHeader('x-phpconsole')));_&&_.apply(this,arguments)};return s.apply(this,arguments)};o=x[p].open;x[p].open=function(a,u){var r=o.apply(this,arguments);c(u)&&this.setRequestHeader('x-phpconsole','1');return r}}(XMLHttpRequest,'prototype','_phpConsoleActivated_')";
self::$output = sprintf("\n<!-- PHP Console -->\n<script>%s</script>", self::$logs);
print(self::$output);
} else {
header("x-phpconsole: " . json_encode(self::$logs));
}
}
@ob_end_flush();
});
set_error_handler([__CLASS__, 'error']);
set_exception_handler([__CLASS__, 'exception']);
}
public static function error($severity, $message, $file, $line, $fatal = false) {
if (error_reporting() & $severity) {
$type = in_array($severity, [E_WARNING, E_COMPILE_WARNING, E_USER_WARNING]) ? 'Warning' : 'Notice';
self::message(['PHP ' . $type . ': ' . $message], $file, $line, 'info');
}
return false;
}
public static function exception($e, $fatal = false) {
error_log($e);
self::$error = true;
$message = sprintf("%s: %s\n%s\n", get_class($e), $e->getMessage(), $e->getTraceAsString());
self::message([$message, $e], $e->getFile(), $e->getLine(), 'warn');
}
static function message($var, $file, $line, $type = 'log') {
if (!self::$debug) return;
eval(sprintf('$var=%s;', preg_replace(
'{([\w\\\\]+)::__set_state(\(array\()}',
'$2"__class__"=>"$1",',
@var_export($var, 1)
)));
self::$logs .= sprintf('(function(){function c(o){if(o&&/j/.test(typeof o)){o.__proto__=null;for(i in o){o[i]=c(o[i])}}return o};for(var i=%d,s="";i--;s+="\n");eval(s+"console.%s.apply(console,c("+%s+"))//# sourceURL="+%s)})();',
max(0, $line - 1),
$type,
json_encode(json_encode($var)),
json_encode("file://" . $file)
);
}
static function log() {
$t = debug_backtrace();
for ($i = 0; isset($t[$i]) && (!isset($t[$i]['file']) || $t[$i]['file'] == __FILE__); $i++);
self::message(func_get_args(), preg_replace("{[:'\s]+}", "_", ($t[$i]['file'])), $t[$i]['line']);
}
static function time ($id) {
self::$timers[$id] = microtime(true);
}
static function timeEnd ($id) {
if (self::$timers[$id]) {
self::log(sprintf("%s: %0.3fms", $id, (microtime(true) - self::$timers[$id]) * 1000));
}
}
}
<?php
if (function_exists("wp")) {
remove_action("shutdown", "wp_ob_end_flush_all", 1);
console::enable();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment