<?php

/**
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2018 Lifestyle Webconsulting GmbH
 * @version    $Id:$
 * @link       http://www.life-style.de
 */

namespace Sso\ApiBundle\Api\Debug;

use Symfony\Component\Debug\Debug;
use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\DebugClassLoader;

class Debug
{

    private static $enabled = false;
    private static $errorHandler;
    private static $errorLevel;

    /**
     * Enables the debug tools.
     *
     * This method registers an error handler and an exception handler.
     *
     * If the Symfony ClassLoader component is available, a special
     * class loader is also registered.
     *
     * @param int $errorReportingLevel The level of error reporting you want
     * @param bool $displayErrors Whether to display errors (for development) or just log them (for production)
     */
    public static function enable($errorReportingLevel = null, $displayErrors = true)
    {
        if (static::$enabled) {
            return;
        }

        static::$enabled = true;

        // Save default error reporting level
        if (null === self::$errorLevel) {
            self::$errorLevel = error_reporting();
        }

        // Set debug reporting level
        error_reporting(-1);

        // Create
        if (null === self::$errorHandler) {
            $handler = new ErrorHandler();
            $handler->setLevel($errorReportingLevel);
            $handler->setDisplayErrors($displayErrors);
            self::$errorHandler = $handler;
        } else {
            $handler = self::$errorHandler;
        }

        ini_set('display_errors', 0);
        set_error_handler(array($handler, 'handle'));
        register_shutdown_function(array($handler, 'handleFatal'));
        $handler->reservedMemory = str_repeat('x', 10240);

        return $handler;

        ErrorHandler::register($errorReportingLevel, $displayErrors);
        if ('cli' !== php_sapi_name()) {
            ExceptionHandler::register();
            // CLI - display errors only if they're not already logged to STDERR
        } elseif ($displayErrors && (!ini_get('log_errors') || ini_get('error_log'))) {
            ini_set('display_errors', 1);
        }

        DebugClassLoader::enable();
    }

}
