Utility classes

2019
/**
 * Logging class to make debugging easier
 */
class Log
{
    const BACKTRACE_LEVEL = 1;
    static $logged = false;

    /**
     * Output one or several entries as JSON
     *
     * @return void
     */
    public static function json()
    {
        header("Content-Type: application/json");
        die(json_encode([static::getBacktrace() => static::parseArgs(func_get_args())]));
    }

    /**
     * Echo a line of text
     *
     * @return void
     */
    public static function console()
    {
        echo "[".static::getBacktrace()."] " . json_encode(static::parseArgs(func_get_args())) . "\n";
        static::$logged = true;
    }

    /**
     * Var_dump a variable
     *
     * @return void
     */
    public static function debug()
    {
        var_dump(static::parseArgs(func_get_args()));
        static::$logged = true;
    }

    /**
     * Dump the arguments in a logfile
     *
     * @return void
     */
    public static function file()
    {
        $path = __DIR__ . "/../debug.log";
        $args = static::parseArgs(func_get_args());
        $content = file_get_contents($path) ?? "";
        $file = fopen($path, "w");
        fwrite($file, $content . json_encode(static::parseArgs(func_get_args())) . "\n");
        fclose($file);
        static::$logged = true;
    }

    /**
     * Clear the log file
     *
     * @return void
     */
    public static function fileClear()
    {
        $path = __DIR__ . "/assets/debug.log";
        $file = fopen($path, "w");
        fwrite($file, "");
        fclose($file);
    }

    /**
     * Process data to be logged
     *
     * @param  array  $args
     * @return void
     */
    public static function parseArgs($args)
    {
        $args = (array) $args;

        if (count($args) === 1) {
            return $args[0];
        }

        return $args;
    }

    /**
     * Get the backtrace as a string, do not include calls made inside this class
     *
     * @return string
     */
    public static function getBacktrace()
    {
        $calls = array_filter(array_map(function ($call) {
            if (!empty($call["file"]) && strpos($call["file"], "Log.php") != false) {
                return false;
            }
            return (!empty($call["file"]) ? basename($call["file"]) : ($call["class"] ?? "")) . ":" . ($call["line"] ?? "");
        }, debug_backtrace()));

        // Keep only the desired amount
        $calls = array_slice($calls, 0, static::BACKTRACE_LEVEL);

        // Return as a string
        return implode(" > ", array_reverse($calls));
    }

    /**
     * Format all log and prevent other display
     *
     * @return void
     */
    public static function clean()
    {
        if (!static::$logged) return;
        header("Content-Type: application/json");
        die();
    }
}