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

Source for file Exception.php

Documentation is available at Exception.php

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
  3. // +----------------------------------------------------------------------+
  4. // | PEAR_Exception                                                       |
  5. // +----------------------------------------------------------------------+
  6. // | Copyright (c) 2004 The PEAR Group                                    |
  7. // +----------------------------------------------------------------------+
  8. // | This source file is subject to version 3.0 of the PHP license,       |
  9. // | that is bundled with this package in the file LICENSE, and is        |
  10. // | available at through the world-wide-web at                           |
  11. // | http://www.php.net/license/3_0.txt.                                  |
  12. // | If you did not receive a copy of the PHP license and are unable to   |
  13. // | obtain it through the world-wide-web, please send a note to          |
  14. // | license@php.net so we can mail you a copy immediately.               |
  15. // +----------------------------------------------------------------------+
  16. // | Authors: Tomas V.V.Cox <cox@idecnet.com>                             |
  17. // |          Hans Lellelid <hans@velum.net>                              |
  18. // |          Bertrand Mansion <bmansion@mamasam.com>                     |
  19. // |          Greg Beaver <cellog@php.net>                                |
  20. // +----------------------------------------------------------------------+
  21. //
  22. // $Id: Exception.php,v 1.4.2.1 2004/10/19 04:13:16 cellog Exp $
  23.  
  24.  
  25. /**
  26.  * Base PEAR_Exception Class
  27.  *
  28.  * WARNING: This code should be considered stable, but the API is
  29.  * subject to immediate and drastic change, so API stability is
  30.  * at best alpha
  31.  *
  32.  * 1) Features:
  33.  *
  34.  * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception))
  35.  * - Definable triggers, shot when exceptions occur
  36.  * - Pretty and informative error messages
  37.  * - Added more context info available (like class, method or cause)
  38.  * - cause can be a PEAR_Exception or an array of mixed
  39.  *   PEAR_Exceptions/PEAR_ErrorStack warnings
  40.  * - callbacks for specific exception classes and their children
  41.  *
  42.  * 2) Ideas:
  43.  *
  44.  * - Maybe a way to define a 'template' for the output
  45.  *
  46.  * 3) Inherited properties from PHP Exception Class:
  47.  *
  48.  * protected $message
  49.  * protected $code
  50.  * protected $line
  51.  * protected $file
  52.  * private   $trace
  53.  *
  54.  * 4) Inherited methods from PHP Exception Class:
  55.  *
  56.  * __clone
  57.  * __construct
  58.  * getMessage
  59.  * getCode
  60.  * getFile
  61.  * getLine
  62.  * getTraceSafe
  63.  * getTraceSafeAsString
  64.  * __toString
  65.  *
  66.  * 5) Usage example
  67.  *
  68.  * <code>
  69.  *  require_once 'PEAR/Exception.php';
  70.  *
  71.  *  class Test {
  72.  *     function foo() {
  73.  *         throw new PEAR_Exception('Error Message', ERROR_CODE);
  74.  *     }
  75.  *  }
  76.  *
  77.  *  function myLogger($pear_exception) {
  78.  *     echo $pear_exception->getMessage();
  79.  *  }
  80.  *  // each time a exception is thrown the 'myLogger' will be called
  81.  *  // (its use is completely optional)
  82.  *  PEAR_Exception::addObserver('myLogger');
  83.  *  $test = new Test;
  84.  *  try {
  85.  *     $test->foo();
  86.  *  } catch (PEAR_Exception $e) {
  87.  *     print $e;
  88.  *  }
  89.  * </code>
  90.  *
  91.  * @since PHP 5
  92.  * @package PEAR
  93.  * @version $Revision: 1.4.2.1 $
  94.  * @author Tomas V.V.Cox <cox@idecnet.com>
  95.  * @author Hans Lellelid <hans@velum.net>
  96.  * @author Bertrand Mansion <bmansion@mamasam.com>
  97.  *
  98.  */
  99. class PEAR_Exception extends Exception
  100. {
  101.     const OBSERVER_PRINT = -2;
  102.     const OBSERVER_TRIGGER = -4;
  103.     const OBSERVER_DIE = -8;
  104.     protected $cause;
  105.     private static $_observers = array();
  106.     private static $_uniqueid = 0;
  107.     private $_trace;
  108.  
  109.     /**
  110.      * Supported signatures:
  111.      * PEAR_Exception(string $message);
  112.      * PEAR_Exception(string $message, int $code);
  113.      * PEAR_Exception(string $message, Exception $cause);
  114.      * PEAR_Exception(string $message, Exception $cause, int $code);
  115.      * PEAR_Exception(string $message, array $causes);
  116.      * PEAR_Exception(string $message, array $causes, int $code);
  117.      */
  118.     public function __construct($message$p2 = null$p3 = null)
  119.     {
  120.         if (is_int($p2)) {
  121.             $code $p2;
  122.             $this->cause = null;
  123.         elseif ($p2 instanceof Exception || is_array($p2)) {
  124.             $code $p3;
  125.             if (is_array($p2&& isset($p2['message'])) {
  126.                 // fix potential problem of passing in a single warning
  127.                 $p2 = array($p2);
  128.             }
  129.             $this->cause = $p2;
  130.         else {
  131.         $code = null;
  132.             $this->cause = null;
  133.         }
  134.         parent::__construct($message$code);
  135.         $this->signal();
  136.     }
  137.  
  138.     /**
  139.      * @param mixed $callback  - A valid php callback, see php func is_callable()
  140.      *                          - A PEAR_Exception::OBSERVER_* constant
  141.      *                          - An array(const PEAR_Exception::OBSERVER_*,
  142.      *                            mixed $options)
  143.      * @param string $label    The name of the observer. Use this if you want
  144.      *                          to remove it later with removeObserver()
  145.      */
  146.     public static function addObserver($callback$label 'default')
  147.     {
  148.         self::$_observers[$label$callback;
  149.     }
  150.  
  151.     public static function removeObserver($label 'default')
  152.     {
  153.         unset(self::$_observers[$label]);
  154.     }
  155.  
  156.     /**
  157.      * @return int unique identifier for an observer
  158.      */
  159.     public static function getUniqueId()
  160.     {
  161.         return self::$_uniqueid++;
  162.     }
  163.  
  164.     private function signal()
  165.     {
  166.         foreach (self::$_observers as $func{
  167.             if (is_callable($func)) {
  168.                 call_user_func($func$this);
  169.                 continue;
  170.             }
  171.             settype($func'array');
  172.             switch ($func[0]{
  173.                 case self::OBSERVER_PRINT :
  174.                     $f (isset($func[1])) $func[1'%s';
  175.                     printf($f$this->getMessage());
  176.                     break;
  177.                 case self::OBSERVER_TRIGGER :
  178.                     $f (isset($func[1])) $func[1: E_USER_NOTICE;
  179.                     trigger_error($this->getMessage()$f);
  180.                     break;
  181.                 case self::OBSERVER_DIE :
  182.                     $f (isset($func[1])) $func[1'%s';
  183.                     die(printf($f$this->getMessage()));
  184.                     break;
  185.                 default:
  186.                     trigger_error('invalid observer type'E_USER_WARNING);
  187.             }
  188.         }
  189.     }
  190.  
  191.     /**
  192.      * Return specific error information that can be used for more detailed
  193.      * error messages or translation.
  194.      *
  195.      * This method may be overridden in child exception classes in order
  196.      * to add functionality not present in PEAR_Exception and is a placeholder
  197.      * to define API
  198.      *
  199.      * The returned array must be an associative array of parameter => value like so:
  200.      * <pre>
  201.      * array('name' => $name, 'context' => array(...))
  202.      * </pre>
  203.      * @return array 
  204.      */
  205.     public function getErrorData()
  206.     {
  207.         return array();
  208.     }
  209.  
  210.     /**
  211.      * Returns the exception that caused this exception to be thrown
  212.      * @access public
  213.      * @return Exception|arrayThe context of the exception
  214.      */
  215.     public function getCause()
  216.     {
  217.         return $this->cause;
  218.     }
  219.  
  220.     /**
  221.      * Function must be public to call on caused exceptions
  222.      * @param array 
  223.      */
  224.     public function getCauseMessage(&$causes)
  225.     {
  226.         $trace $this->getTraceSafe();
  227.         $causes[= array('class'   => get_class($this),
  228.                           'message' => $this->message,
  229.                           'file'    => $trace[0]['file'],
  230.                           'line'    => $trace[0]['line']);
  231.         if ($this->cause instanceof PEAR_Exception{
  232.             $this->cause->getCauseMessage($causes);
  233.         }
  234.         if (is_array($this->cause)) {
  235.             foreach ($this->cause as $cause{
  236.                 if ($cause instanceof PEAR_Exception{
  237.                     $cause->getCauseMessage($causes);
  238.                 elseif (is_array($cause&& isset($cause['message'])) {
  239.                     // PEAR_ErrorStack warning
  240.                     $causes[= array(
  241.                         'class' => $cause['package'],
  242.                         'message' => $cause['message'],
  243.                         'file' => isset($cause['context']['file']?
  244.                                             $cause['context']['file':
  245.                                             'unknown',
  246.                         'line' => isset($cause['context']['line']?
  247.                                             $cause['context']['line':
  248.                                             'unknown',
  249.                     );
  250.                 }
  251.             }
  252.         }
  253.     }
  254.  
  255.     public function getTraceSafe()
  256.     {   
  257.         if (!isset($this->_trace)) {
  258.             $this->_trace $this->getTrace();
  259.             if (empty($this->_trace)) {
  260.                 $backtrace debug_backtrace();
  261.                 $this->_trace = array($backtrace[count($backtrace)-1]);
  262.             }
  263.         }
  264.         return $this->_trace;
  265.     }
  266.  
  267.     public function getErrorClass()
  268.     {
  269.         $trace $this->getTraceSafe();
  270.         return $trace[0]['class'];
  271.     }
  272.  
  273.     public function getErrorMethod()
  274.     {
  275.         $trace $this->getTraceSafe();
  276.         return $trace[0]['function'];
  277.     }
  278.  
  279.     public function __toString()
  280.     {
  281.         if (isset($_SERVER['REQUEST_URI'])) {
  282.             return $this->toHtml();
  283.         }
  284.         return $this->toText();
  285.         }
  286.  
  287.     public function toHtml()
  288.     {
  289.         $trace $this->getTraceSafe();
  290.         $causes = array();
  291.         $this->getCauseMessage($causes);
  292.         $html =  '<table border="1" cellspacing="0">' "\n";
  293.         foreach ($causes as $i => $cause{
  294.             $html .= '<tr><td colspan="3" bgcolor="#ff9999">'
  295.                . str_repeat('-'$i' <b>' $cause['class''</b>: '
  296.                . htmlspecialchars($cause['message']' in <b>' $cause['file''</b> '
  297.                . 'on line <b>' $cause['line''</b>'
  298.                . "</td></tr>\n";
  299.         }
  300.         $html .= '<tr><td colspan="3" bgcolor="#aaaaaa" align="center"><b>Exception trace</b></td></tr>' "\n"
  301.                . '<tr><td align="center" bgcolor="#cccccc" width="20"><b>#</b></td>'
  302.                . '<td align="center" bgcolor="#cccccc"><b>Function</b></td>'
  303.                . '<td align="center" bgcolor="#cccccc"><b>Location</b></td></tr>' "\n";
  304.  
  305.         foreach ($trace as $k => $v{
  306.             $html .= '<tr><td align="center">' $k '</td>'
  307.                    . '<td>';
  308.             if (!empty($v['class'])) {
  309.                 $html .= $v['class'$v['type'];
  310.             }
  311.             $html .= $v['function'];
  312.             $args = array();
  313.             if (!empty($v['args'])) {
  314.                 foreach ($v['args'as $arg{
  315.                     if (is_null($arg)) $args['null';
  316.                     elseif (is_array($arg)) $args['Array';
  317.                     elseif (is_object($arg)) $args['Object('.get_class($arg).')';
  318.                     elseif (is_bool($arg)) $args[$arg 'true' 'false';
  319.                     elseif (is_int($arg|| is_double($arg)) $args[$arg;
  320.                     else {
  321.                         $arg = (string)$arg;
  322.                         $str htmlspecialchars(substr($arg016));
  323.                         if (strlen($arg> 16$str .= '&hellip;';
  324.                         $args["'" $str "'";
  325.                     }
  326.                 }
  327.             }
  328.             $html .= '(' implode(', ',$args')'
  329.                    . '</td>'
  330.                    . '<td>' $v['file'':' $v['line''</td></tr>' "\n";
  331.         }
  332.         $html .= '<tr><td align="center">' ($k+1'</td>'
  333.                . '<td>{main}</td>'
  334.                . '<td>&nbsp;</td></tr>' "\n"
  335.                . '</table>';
  336.         return $html;
  337.     }
  338.  
  339.     public function toText()
  340.     {
  341.         $causes = array();
  342.         $this->getCauseMessage($causes);
  343.         $causeMsg '';
  344.         foreach ($causes as $i => $cause{
  345.             $causeMsg .= str_repeat(' '$i$cause['class'': '
  346.                    . $cause['message'' in ' $cause['file']
  347.                    . ' on line ' $cause['line'"\n";
  348.         }
  349.         return $causeMsg $this->getTraceAsString();
  350.     }
  351. }
  352.  
  353. ?>

Documentation generated on Mon, 11 Mar 2019 13:58:37 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.