<?php
/**
 * Обработчик эксепшенов
 *
 * @copyright NetMonsters <team@netmonsters.ru>
 * @link
 * @package Majestic
 * @subpackage Core
 * @since
 * @version SVN: $Id$
 * @filesource $URL$
 */
class MJException extends Exception
{
    private $line_range = 6;

    public function terminate()
    {
        if (!DEBUG_ENABLE) {
            trigger_error($this->getMessage());
            throw new StaticPageException(500);
        }

        $return = "<b>MJ Error:</b> ";
        $return .= str_replace("\n", "<br/>\n", $this->getMessage())."<br>\n";

        $trace = $this->getTrace();

        $file = reset($trace);

        //смещение в трейсе, указаное при вызове эксепшена (2й параметр). Нужно для более инофрмативного вывода
        if ($shift = abs($this->getCode())) {
            while($shift--) {
                $file = next($trace);
            }
        }

        if ($fp = fopen($file['file'], 'r')) {
            $error_line = $file['line'];
            $start = $error_line - $this->line_range;
            $end = $error_line + $this->line_range;
            $i = 1;
            $return .= "<pre style=\"background-color:#e4e4e4\">";
            while ($line = fgets($fp, 4096) and $i<=$end) {
                $line = htmlspecialchars($line);
                if ($i >= $start && $i <= $end) {
                    if ($i == $error_line) $return .= '<div style="background-color:#cccccc">'.$i.'  '.$line.'</div>';
                    else $return .= $i.'  '.$line;
                }
                $i++;
            }
            $return .= "</pre>";
            fclose($fp);
        }

        $return .= '<table border="1" cellpadding="2" cellspacing="0"> <caption><b>Backtrace</b></caption>';
        $return .= "\n<tr><td><b>".$this->getFile().'</b></td><td><b>'.$this->getLine().'</b></td></tr>';
        foreach($trace as $row) {
            if (isset($row['file'])) { //throwing exception from __call method will not return file and line
                $return .= "\n<tr".($file['file'] == $row['file'] ? ' style="background-color:#ffcccc"': '')."><td>".$row['file'].'</td><td>'.$row['line'].'</td></tr>';
            }
        }
        return $return . '</table>';
    }
}
?>