energine
[ class tree: energine ] [ index: energine ] [ all elements ]

Source for file BaseException.class.php

Documentation is available at BaseException.class.php

  1. <?php
  2.  
  3. /**
  4.  * Класс BaseException
  5.  *
  6.  * @package energine
  7.  * @subpackage core
  8.  * @author 1m.dm
  9.  * @copyright Energine 2006
  10.  * @version $Id$
  11.  */
  12.  
  13. //require_once('core/framework/DBWorker.class.php');
  14. //require_once('core/framework/Transformer.class.php');
  15. //require_once('core/framework/Response.class.php');
  16. //require_once('core/framework/Mail.class.php');
  17. //require_once('core/framework/Language.class.php');
  18. /**
  19.  * Базовое исключение.
  20.  *
  21.  * @package energine
  22.  * @subpackage core
  23.  * @author 1m.dm
  24.  */
  25. class BaseException extends Exception {
  26.  
  27.     /**
  28.      * XSLT-документ для страницы ошибки
  29.      */
  30.     const ERROR_TRANSFORMER = 'error_page.xslt';
  31.  
  32.     /**
  33.      * Критическая ошибка
  34.      */
  35.     const ERR_CRITICAL = 0;
  36.  
  37.     /**
  38.      * Ошибка 404 - страницы не существует
  39.      */
  40.     const ERR_404 = 1;
  41.  
  42.     /**
  43.      * Ошибка 403 - нет прав на просмотр страницы
  44.      */
  45.     const ERR_403 = 2;
  46.  
  47.     /**
  48.      * Ошибка при работе с БД
  49.      */
  50.     const ERR_DB = 3;
  51.  
  52.     /**
  53.      * Ошибка разработчика, где-то что-то неверно написано :)
  54.      */
  55.     const ERR_DEVELOPER = 4;
  56.  
  57.     /**
  58.      * Предупреждение
  59.      */
  60.     const ERR_WARNING = 10;
  61.  
  62.     /**
  63.      * Замечание
  64.      */
  65.     const ERR_NOTICE = 20;
  66.  
  67.     /**
  68.      * Ошибка, связанная с мультиязычностью. Возникает при обработке другой
  69.      * ошибки и отсутствия для неё переводов. Без ERR_LANG возможет уход
  70.      * в рекурсию и полный пиздец.
  71.      *
  72.      * Данная ошибка касается исключительно разработчиков системы.
  73.      *
  74.      * @todo сделать хоть что-нибудь! :)
  75.      */
  76.     const ERR_LANG = 5;
  77.  
  78.     /**
  79.      * Когда режим отладки включен:
  80.      *
  81.      *     1. Можно вывести XML-документ страницы добавив к query-части URI
  82.      *        параметр 'debug'.
  83.      *     2. При обработке системных ошибок выводится максимально подробная
  84.      *        информация о возникшей ошибке.
  85.      *
  86.      * @access private
  87.      * @var boolean флаг режима отладки
  88.      */
  89.     private $isDebugEnabled = true;
  90.  
  91.     /**
  92.      * @access protected
  93.      * @var Response экземпляр объекта Response
  94.      */
  95.     protected $response;
  96.  
  97.     /**
  98.      * @access protected
  99.      * @var boolean флаг режима вывода XML-документа страницы
  100.      * @todo плохое имя
  101.      */
  102.     protected $isXML;
  103.  
  104.     /**
  105.      * @access protected
  106.      * @var DOMDocument 
  107.      */
  108.     protected $doc;
  109.  
  110.     /**
  111.      * @access protected
  112.      * @var mixed дополнительная информация об ошибке
  113.      */
  114.     protected $customMessages = array();
  115.  
  116.     /**
  117.      * Конструктор класса.
  118.      *
  119.      * @access public
  120.      * @param string $message 
  121.      * @param int $code 
  122.      * @param mixed $customMessages 
  123.      * @return void 
  124.      * @todo определиться с $customMessages: это mixed или array?
  125.      */
  126.     public function __construct($message$code self::ERR_CRITICAL$customMessages null{
  127.         $this->isDebugEnabled = (bool)Object::_getConfigValue('site.debug');
  128.  
  129.         $this->response = Response::getInstance();
  130.         $this->isXML = isset($_GET['debug']);
  131.         $this->doc = new DOMDocument('1.0''UTF-8');
  132.         if (isset($customMessages)) {
  133.             if (!is_array($customMessages)) {
  134.                 $this->customMessages = array($customMessages);
  135.             }
  136.             else {
  137.                 $this->customMessages = $customMessages;
  138.             }
  139.         }
  140.  
  141.         if ($code == self::ERR_LANG{
  142.             $message DBWorker::_translate($messageLanguage::getInstance()->getDefault());
  143.         }
  144.         elseif ($code == self::ERR_403{
  145.             $this->response->setStatus(403);
  146.         }
  147.         elseif ($code == self::ERR_404{
  148.             $this->response->setStatus(404);
  149.         }
  150.         elseif ($code != self::ERR_DB {
  151.             $message DBWorker::_translate($messageLanguage::getInstance()->getCurrent());
  152.         }
  153.  
  154.  
  155.         parent::__construct($message$code);
  156.     }
  157.  
  158.     /**
  159.      * Возвращает дополнительную информацию об ошибке.
  160.      *
  161.      * @access public
  162.      * @return string 
  163.      * @todo переименовать в getCustomMessages
  164.      */
  165.     public function getCustomMessage({
  166.         return $this->customMessages;
  167.     }
  168.  
  169.     /**
  170.      * Отправляет уведомление о ошибке
  171.      *
  172.      * @return void 
  173.      * @access private
  174.      */
  175.  
  176.     private function sendNotification({
  177.         $mail new Mail();
  178.         $projectName ($fake Object::_getConfigValue('project.name'))?$fake:$_SERVER['HTTP_HOST'];
  179.         $from Object::_getConfigValue('mail.from');
  180.         $customMessage implode("\r\n"$this->getCustomMessage());
  181.  
  182.         $body sprintf("Project:%s\r\nCode:%s\r\nMessage:%s\r\nCustomMessage:%s\r\n,File:%s\r\nLine:%s\r\nTrace:%s"$projectName$this->getCode()$this->getMessage()$customMessage,$this->getFile()$this->getLine()$this->getTraceAsString());
  183.         $mail->setText($body)
  184.             ->setFrom($from$from)
  185.             ->addTo(Object::_getConfigValue('mail.feedback'))
  186.             ->setSubject($projectName.' Error Notification:'.$this->getMessage())
  187.             ->send();
  188.     }
  189.     /**
  190.      * Формирует XML-представление ошибки.
  191.      *
  192.      * @access protected
  193.      * @return void 
  194.      */
  195.     protected function build({
  196.         $request Request::getInstance();
  197.  
  198.         $dom_errors $this->doc->createElement('errors');
  199.         $dom_errors->setAttribute('uri'$request->getPath(Request::PATH_WHOLEtrue));
  200.         $dom_errors->setAttribute('base'$request->getBasePath());
  201.         $dom_errors->setAttribute('debug'$this->isDebugEnabled);
  202.  
  203.         $dom_error $this->doc->createElement('error');
  204.         $dom_error->setAttribute('code'$this->getCode());
  205.         $dom_error->setAttribute('file'$this->getFile());
  206.         $dom_error->setAttribute('line'$this->getLine());
  207.  
  208.         $dom_error->appendChild(
  209.             $this->doc->createElement('message'$this->getMessage())
  210.         );
  211.  
  212.         $customMessages $this->getCustomMessage();
  213.         if ($customMessages{
  214.             $dom_customMessages $this->doc->createElement('customMessages');
  215.             if (is_array($customMessages)) {
  216.                 foreach ($customMessages as $customMessage{
  217.                     $dom_customMessages->appendChild(
  218.                         $this->doc->createElement('customMessage'$customMessage)
  219.                     );
  220.                 }
  221.             }
  222.             else {
  223.                 $dom_customMessages->nodeValue $customMessages;
  224.             }
  225.             $dom_error->appendChild($dom_customMessages);
  226.         }
  227.  
  228.         $dom_errors->appendChild($dom_error);
  229.         $this->doc->appendChild($dom_errors);
  230.     }
  231.  
  232.     /**
  233.      * Обрабатывает ошибку путём её вывода :)
  234.      *
  235.      * @access public
  236.      * @return void 
  237.      */
  238.     public function handle({
  239.         if (!in_array($this->getCode()array(self::ERR_403self::ERR_404self::ERR_NOTICEself::ERR_WARNING)) && !$this->isDebugEnabled{
  240.             $this->sendNotification();
  241.         }
  242.  
  243.         $this->build();
  244.  
  245.         if ($this->isDebugEnabled && $this->isXML{
  246.             $this->response->setHeader('Content-Type''text/xml; charset=UTF-8');
  247.             $result $this->doc->saveXML();
  248.         }
  249.         else {
  250.             $this->response->setHeader('Content-Type''text/html; charset=UTF-8');
  251.             $transformer new Transformer;
  252.             $result $transformer->transform($this->docself::ERROR_TRANSFORMER);
  253.         }
  254.  
  255.         $this->response->write($result);
  256.         $this->response->commit();
  257.     }
  258. }
В создании документации нам помог: phpDocumentor