<?php
/*
 * Functions relative to debugging
 */

/**
 * Add a message to the debug log
 *
 * When in debug mode (YOURLS_DEBUG == true at startup or yourls_debug_mode() set to true later on), the debug log is
 * echoed in yourls_html_footer().
 * Log messages are appended to $ydb->debug_log array, which is instantiated within class Database\YDB
 *
 * @since 1.7
 * @param string $msg Message to add to the debug log
 * @return string The message itself
 */
function yourls_debug_log(string $msg): string {
    if (yourls_get_debug_mode()) {
        yourls_do_action('debug_log', $msg);
        yourls_get_db('read-debug_log')->getProfiler()->getLogger()->log('debug', $msg);
    }
    return $msg;
}

/**
 * Get the debug log
 *
 * @since  1.7.3
 * @return array
 */
function yourls_get_debug_log(): array {
    return yourls_get_db('read-get_debug_log')->getProfiler()->getLogger()->getMessages();
}

/**
 * Get number of SQL queries performed
 *
 * @return int
 */
function yourls_get_num_queries(): int {
    return yourls_apply_filter( 'get_num_queries', yourls_get_db('read-get_num_queries')->get_num_queries() );
}

/**
 * Debug mode set
 *
 * @since 1.7.3
 * @param bool $bool Debug on or off
 * @return void
 */
function yourls_debug_mode(bool $bool): void {
    // log queries if true
    yourls_get_db('read-debug_mode')->getProfiler()->setActive( (bool)$bool );

    // report notices if true
    $level = $bool ? -1 : ( E_ERROR | E_PARSE );
    error_reporting( $level );
}

/**
 * Return YOURLS debug mode
 *
 * @since 1.7.7
 * @return bool
 */
function yourls_get_debug_mode(): bool {
    return yourls_get_db('read-debug_mode')->getProfiler()->isActive();
}
