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.2 2004/12/31 19:01:52 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.2 $
  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.         $cause = array('class'   => get_class($this),
  228.                        'message' => $this->message,
  229.                        'file' => 'unknown',
  230.                        'line' => 'unknown');
  231.         if (isset($trace[0])) {
  232.             if (isset($trace[0]['file'])) {
  233.                 $cause['file'$trace[0]['file'];
  234.                 $cause['line'$trace[0]['line'];
  235.             }
  236.         }
  237.         if ($this->cause instanceof PEAR_Exception{
  238.             $this->cause->getCauseMessage($causes);
  239.         }
  240.         if (is_array($this->cause)) {
  241.             foreach ($this->cause as $cause{
  242.                 if ($cause instanceof PEAR_Exception{
  243.                     $cause->getCauseMessage($causes);
  244.                 elseif (is_array($cause&& isset($cause['message'])) {
  245.                     // PEAR_ErrorStack warning
  246.                     $causes[= array(
  247.                         'class' => $cause['package'],
  248.                         'message' => $cause['message'],
  249.                         'file' => isset($cause['context']['file']?
  250.                                             $cause['context']['file':
  251.                                             'unknown',
  252.                         'line' => isset($cause['context']['line']?
  253.                                             $cause['context']['line':
  254.                                             'unknown',
  255.                     );
  256.                 }
  257.             }
  258.         }
  259.     }
  260.  
  261.     public function getTraceSafe()
  262.     {   
  263.         if (!isset($this->_trace)) {
  264.             $this->_trace $this->getTrace();
  265.             if (empty($this->_trace)) {
  266.                 $backtrace debug_backtrace();
  267.                 $this->_trace = array($backtrace[count($backtrace)-1]);
  268.             }
  269.         }
  270.         return $this->_trace;
  271.     }
  272.  
  273.     public function getErrorClass()
  274.     {
  275.         $trace $this->getTraceSafe();
  276.         return $trace[0]['class'];
  277.     }
  278.  
  279.     public function getErrorMethod()
  280.     {
  281.         $trace $this->getTraceSafe();
  282.         return $trace[0]['function'];
  283.     }
  284.  
  285.     public function __toString()
  286.     {
  287.         if (isset($_SERVER['REQUEST_URI'])) {
  288.             return $this->toHtml();
  289.         }
  290.         return $this->toText();
  291.         }
  292.  
  293.     public function toHtml()
  294.     {
  295.         $trace $this->getTraceSafe();
  296.         $causes = array();
  297.         $this->getCauseMessage($causes);
  298.         $html =  '<table border="1" cellspacing="0">' "\n";
  299.         foreach ($causes as $i => $cause{
  300.             $html .= '<tr><td colspan="3" bgcolor="#ff9999">'
  301.                . str_repeat('-'$i' <b>' $cause['class''</b>: '
  302.                . htmlspecialchars($cause['message']' in <b>' $cause['file''</b> '
  303.                . 'on line <b>' $cause['line''</b>'
  304.                . "</td></tr>\n";
  305.         }
  306.         $html .= '<tr><td colspan="3" bgcolor="#aaaaaa" align="center"><b>Exception trace</b></td></tr>' "\n"
  307.                . '<tr><td align="center" bgcolor="#cccccc" width="20"><b>#</b></td>'
  308.                . '<td align="center" bgcolor="#cccccc"><b>Function</b></td>'
  309.                . '<td align="center" bgcolor="#cccccc"><b>Location</b></td></tr>' "\n";
  310.  
  311.         foreach ($trace as $k => $v{
  312.             $html .= '<tr><td align="center">' $k '</td>'
  313.                    . '<td>';
  314.             if (!empty($v['class'])) {
  315.                 $html .= $v['class'$v['type'];
  316.             }
  317.             $html .= $v['function'];
  318.             $args = array();
  319.             if (!empty($v['args'])) {
  320.                 foreach ($v['args'as $arg{
  321.                     if (is_null($arg)) $args['null';
  322.                     elseif (is_array($arg)) $args['Array';
  323.                     elseif (is_object($arg)) $args['Object('.get_class($arg).')';
  324.                     elseif (is_bool($arg)) $args[$arg 'true' 'false';
  325.                     elseif (is_int($arg|| is_double($arg)) $args[$arg;
  326.                     else {
  327.                         $arg = (string)$arg;
  328.                         $str htmlspecialchars(substr($arg016));
  329.                         if (strlen($arg> 16$str .= '&hellip;';
  330.                         $args["'" $str "'";
  331.                     }
  332.                 }
  333.             }
  334.             $html .= '(' implode(', ',$args')'
  335.                    . '</td>'
  336.                    . '<td>' $v['file'':' $v['line''</td></tr>' "\n";
  337.         }
  338.         $html .= '<tr><td align="center">' ($k+1'</td>'
  339.                . '<td>{main}</td>'
  340.                . '<td>&nbsp;</td></tr>' "\n"
  341.                . '</table>';
  342.         return $html;
  343.     }
  344.  
  345.     public function toText()
  346.     {
  347.         $causes = array();
  348.         $this->getCauseMessage($causes);
  349.         $causeMsg '';
  350.         foreach ($causes as $i => $cause{
  351.             $causeMsg .= str_repeat(' '$i$cause['class'': '
  352.                    . $cause['message'' in ' $cause['file']
  353.                    . ' on line ' $cause['line'"\n";
  354.         }
  355.         return $causeMsg $this->getTraceAsString();
  356.     }
  357. }
  358.  
  359. ?>

Documentation generated on Mon, 11 Mar 2019 14:23:57 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.