Last active
September 3, 2017 04:58
-
-
Save SamuelDavis/5c75c3cc59cabadd8e259a265ceec9f1 to your computer and use it in GitHub Desktop.
A module of helpful methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Debug | |
{ | |
public static $TIMESTAMPS = []; | |
public static function timestamp(string $key = null) | |
{ | |
$key = $key ?: count(static::$TIMESTAMPS); | |
static::$TIMESTAMPS[$key] = microtime(true); | |
} | |
public static function computeTimeTaken(): array | |
{ | |
$res = []; | |
$keys = array_keys(static::$TIMESTAMPS); | |
foreach ($keys as $i => $key) { | |
$last = static::$TIMESTAMPS[$keys[$i - 1] ?? $key]; | |
$curr = static::$TIMESTAMPS[$key]; | |
$res[$key] = $curr - $last; | |
} | |
return $res; | |
} | |
public static function pretty($thing): string | |
{ | |
return str_replace([ | |
'{', '}', ':', | |
], [ | |
'[', ']', ' =>', | |
], json_encode($thing, JSON_PRETTY_PRINT)); | |
} | |
public static function printPreparedStatement(string $query, array $bindings = []): string | |
{ | |
if (!$bindings) { | |
return $query; | |
} | |
$find = ['(', ')']; | |
$replace = ["(\n", "\n)"]; | |
$breakBefore = ['from', 'where', 'and', 'group by']; | |
foreach ($breakBefore as $breakWord) { | |
$find[] = "{$breakWord}"; | |
$replace[] = "\n{$breakWord}"; | |
} | |
$query = str_replace($find, $replace, $query); | |
$depth = 0; | |
$query = array_reduce(explode("\n", $query), function (string $acc, string $line) use (&$depth) { | |
$res = $acc . str_repeat("\t", $depth) . trim($line) . "\n"; | |
if (substr($line, 0, 1) === ')') { | |
$depth--; | |
} | |
if (substr($line, -1) === '(') { | |
$depth++; | |
} | |
return $res; | |
}, ''); | |
return '<pre>' . array_reduce($bindings, function (string $query, $binding = null) { | |
return preg_replace('/\?/', json_encode($binding), $query, 1); | |
}, $query) . '</pre>'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment