<?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\Error;

use Symfony\Component\Debug\ErrorHandler;

/**
 * Class Handler
 * @package Sso\ApiBundle\Api\Error
 */
class Handler extends ErrorHandler
{

    /**
     * Registers the error handler.
     *
     * @param int $level The level at which the conversion to Exception is done (null to use the error_reporting() value and 0 to disable)
     * @param bool $displayErrors Display errors (for dev environment) or just log them (production usage)
     *
     * @return ErrorHandler The registered error handler
     */
    public static function register($level = null, $displayErrors = true)
    {
        $handler = new static();
        $handler->setLevel($level);
        $handler->setDisplayErrors($displayErrors);

        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;
    }

    public function handle($level, $message, $file = 'unknown', $line = 0, $context = array())
    {
        $this->_sendErrorXml('crit01');
        return false;
    }

    public function handleFatal()
    {
        $this->_sendErrorXml('crit02');
    }

    protected function _sendErrorXml($errorCode)
    {
        if (!headers_sent()) {
            header("Content-type: text/xml");
        }
        echo '<?xml version="1.0" encoding="UTF-8" ?>
<ErrorResponse>
	<Status>Error</Status>
	<ErrorType>internal</ErrorType>
	<RequestController>unknown</RequestController>
	<RequestAction>unknown</RequestAction>
	<Trackid>unknown</Trackid>
	<Date></Date>
	<Errors>
		<Error>
			<ErrorCode><![CDATA[' . $errorCode . ']]></ErrorCode>
			<ShortMessage><![CDATA[Critical error]]></ShortMessage>
			<LongMessage><![CDATA[An unknown critical error has occured.]]></LongMessage>
		</Error>
	</Errors>
</ErrorResponse>';
    }

}
