<?php
class PhonalisaErrorHandler extends CErrorHandler
{
    protected function handleError($event)
    {
        $alert = new Alert();
        $alert->level = $this->getAlertLevelFromErrorCode($event->code);
        $alert->component = Alert::COMPONENT_WEBGUI;
        $alert->shortDescr = $this->getHumanReadableErrorCode($event->code) . " : " . $event->message;
        $alert->descr = $this->getBackTraceString();
        $alert->created = PhonalisaDate::newServerDate();
        $alert->save();
        parent::handleError($event);
    }
    
    private function getBackTraceString() {
        $trace=debug_backtrace();
        $traceString='';
        foreach($trace as $i=>$t)
        {
            if(!isset($t['file']))
                $trace[$i]['file']='unknown';

            if(!isset($t['line']))
                $trace[$i]['line']=0;

            if(!isset($t['function']))
                $trace[$i]['function']='unknown';

            $traceString.="#$i {$trace[$i]['file']}({$trace[$i]['line']}): ";
            if(isset($t['object']) && is_object($t['object']))
                $traceString.=get_class($t['object']).'->';
            $traceString.="{$trace[$i]['function']}()\n";

            unset($trace[$i]['object']);
        }
        return $traceString;
    } 
    
    private function getHumanReadableErrorCode($code) {
        switch($code)
        {
            case E_WARNING:
                    $type = 'PHP warning';
                    break;
            case E_NOTICE:
                    $type = 'PHP notice';
                    break;
            case E_USER_ERROR:
                    $type = 'User error';
                    break;
            case E_USER_WARNING:
                    $type = 'User warning';
                    break;
            case E_USER_NOTICE:
                    $type = 'User notice';
                    break;
            case E_RECOVERABLE_ERROR:
                    $type = 'Recoverable error';
                    break;
            default:
                    $type = 'PHP error';
        }
        return $type;
    }
    
    private function getAlertLevelFromErrorCode($code) {
        switch($code)
        {
            case E_WARNING:
            case E_USER_WARNING:
                    $level = Alert::LEVEL_WARNING;
                    break;
            case E_NOTICE:
            case E_USER_NOTICE:
                    $level = Alert::LEVEL_INFO;
                    break;
            case E_USER_ERROR:
            case E_RECOVERABLE_ERROR:
                    $level = Alert::LEVEL_ERROR;
                    break;
            default:
                    $level = Alert::LEVEL_ERROR;
        }
        return $level;
    }
    
}