Télécharger ang Class Debug

Avatar de gene69
Membre Expert
Mise à jour le : 20/08/2011  ·   Licence : GPL  ·   Téléchargé 24 fois   ·   16 Ko  +
Présentation
  • utilisez un autoloader de classe pour vous simplifier la vie
  • j'utilise ça preque exclusivement en version statique, pour faire des sites spaghettis
  • Debug::var_dump()
  • Debug::here() si vous utilisez des output buffer (ob_start)
  • Debug::printStack()
  • Debug::describeState()
  • c'est documenté pour phpdocumentor (enfin la partie la plus utile = statique )
  • s'active et se desactive partout sans pb de visibilité avec Debug::$inhibit
  • fonctionne dans le shell Debug::outputHTML



je suis pointilleux pour le coté GPL2. je répond au message par MP si vous trouvez un bug (dans la classe, pas dans votre code).
Téléchargement :






		
  1. <?php
  2. /**
  3.  * @package framework
  4.  * @author Pierre-Emmanuel Périllon
  5.  * @license GPL2
  6.  *
  7.  * This program is free software; you can redistribute it and/or modify
  8.  * it under the terms of the GNU General Public License as published by
  9.  * the Free Software Foundation; either version 2 of the License, or
  10.  * (at your option) any later version.
  11.  *
  12.  * This program is distributed in the hope that it will be useful,
  13.  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14.  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15.  * GNU General Public License for more details.
  16.  *
  17.  * You should have received a copy of the GNU General Public License
  18.  * along with this program; if not, write to the Free Software
  19.  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  20.  * MA 02110-1301, USA.
  21.  **/
  22. /**
  23.  * @see __autoload()
  24.  * */
  25. require_once('autoload.inc.php');
  26. /**
  27.  * @package framework
  28.  */
  29. //class DebugException extends MyException{};
  30.  
  31. /**
  32.  * This class allow to print lots of debug info in different context (with static method)
  33.  * and allow to debug $_SESSION by initialising $_SESSION = new Debug();
  34.  * @package framework
  35.  */
  36. class Debug extends ArrayObject implements Serializable
  37. {
  38.  
  39. /**
  40. * @var boolean inhibe le fonctionnement de la classe lorsqu'à vrai.
  41. * */
  42. static $inhibit;
  43.  
  44. /**
  45. * @var this is a filename where i can up ArrayObject info
  46. * */
  47. static $debug_outup;
  48.  
  49. /**
  50. * @var ressource this is a file
  51. * */
  52. private $fp;
  53.  
  54. /**
  55. * @var string identifiant unique de l'objet.
  56. * */
  57. private $uid;
  58.  
  59. /*****/
  60. static $outputHTML = true;
  61.  
  62.  
  63. /* Méthodes */
  64. function __construct ( )
  65. {
  66. $this->init();
  67. $this->writeLog(__FUNCTION__);
  68. parent::__construct();
  69. }
  70.  
  71.  
  72.  
  73. function __destruct( )
  74. {
  75. $this->writeLog(__FUNCTION__);
  76. if ( is_resource( $this->fp ) )
  77. {
  78. fclose($this->fp);
  79. }
  80. $this->fp = null;
  81. }
  82.  
  83.  
  84. function __toString()
  85. {
  86. return $this->uid;
  87. }
  88.  
  89. function append ( $value )
  90. {
  91. $this->writeLog(__FUNCTION__);
  92. parent::append($values);
  93. }
  94.  
  95. function asort ()
  96. {
  97. $this->writeLog(__FUNCTION__);
  98. parent::asort();
  99. }
  100.  
  101. //function count ( )
  102.  
  103. function exchangeArray (&$input )
  104. {
  105. $this->writeLog(__FUNCTION__);
  106. return parent::exchangeArray ( $input );
  107. }
  108. //function getFlags ( void )
  109. //function getIterator ( void )
  110. //function getIteratorClass ( void )
  111.  
  112. function init()
  113. {
  114. if ( !empty(self::$debug_outup ) )
  115. {
  116. $this->fp = fopen( self::$debug_outup, 'a' );
  117. if ( $this->fp === false )
  118. {
  119. throw new Exception("ne peut ouvrir le fichier de log");
  120. }
  121. }
  122. else
  123. {
  124. $this->fp = null;
  125. }
  126. $this->uid = uniqid('#');
  127. }
  128.  
  129. function ksort ( )
  130. {
  131. $this->writeLog(__FUNCTION__);
  132. parent::ksort();
  133. }
  134.  
  135. function natcasesort ( )
  136. {
  137. $this->writeLog(__FUNCTION__);
  138. parent::natcasesort ( );
  139. }
  140.  
  141. function natsort ( )
  142. {
  143. $this->writeLog(__FUNCTION__);
  144. parent::natsort ( );
  145. }
  146.  
  147. // function offsetExists ( mixed $index )
  148. // function offsetGet ( mixed $index )
  149.  
  150. function offsetSet ( $index , $newval )
  151. {
  152. $this->writeLog(__FUNCTION__ , serialize($index).'=>'.serialize($newval) );
  153. return parent::offsetSet( $index , $newval);
  154. }
  155.  
  156. function offsetUnset ( $index )
  157. {
  158. $this->writeLog(__FUNCTION__, $index );
  159. parent::offsetUnset ( $index );
  160. }
  161.  
  162.  
  163. function serialize ( )
  164. {
  165. $this->writeLog(__FUNCTION__);
  166. return serialize($this->getArrayCopy());
  167. }
  168.  
  169. // function setFlags ( int $flags )
  170. // function setIteratorClass ( string $iterator_class )
  171.  
  172. function uasort ( $cmp_function )
  173. {
  174. $this->writeLog(__FUNCTION__);
  175. parent:: uasort( );
  176. }
  177.  
  178. function uksort ( $cmp_function )
  179. {
  180. $this->writeLog(__FUNCTION__);
  181. parent:: uksort ( );
  182. }
  183.  
  184.  
  185. /**
  186. * ce serrait tres beau si ça marchait comme ça.
  187. * */
  188. function unserialize ( $serialized )
  189. {
  190. unserialize( $serialized);
  191. $this->init();
  192. $this->writeLog(__FUNCTION__);
  193. }
  194.  
  195.  
  196.  
  197. /***
  198. * tue le script en cours.
  199. *
  200. * @access public
  201. * @static
  202. * @return void
  203. * @uses Debug::getCaller()
  204. ***/
  205. static public function kill()
  206. {
  207. if ( self::$inhibit ) return ;
  208.  
  209. echo '
  210. <!-- SCRIPT KILLED !!! -->
  211. ',$tmp = self::getCaller(),'
  212. <!-- will kown unload outputBuffer -->
  213. ';
  214.  
  215. $buff = array();
  216. while( ob_get_level() > 1 )
  217. {
  218. echo '
  219. <!-- new Buffer -->
  220. }
  221. echo '<!-- SCRIPT KILLED !!!
  222. ' ,$tmp ,'
  223. -->';
  224. }
  225.  
  226.  
  227. static function describeState( $e = null )
  228. {
  229. Debug::printCaller(1);
  230. echo '
  231. <div>
  232. <strong>Informations</strong>
  233. <p>
  234. Généré à ',date('r'),' <br />
  235. have fun! The script is runned by php version ',phpversion(),'</p>
  236. <strong>Exception</strong>
  237. <pre>',is_null($e)?'no exception':htmlspecialchars($e),'</pre>
  238. <strong>Input: Session</strong>
  239. <pre>',htmlspecialchars( isset($_SESSION) ?print_r($_SESSION,true):'no session' ),'</pre>
  240. <strong>Input: GET</strong>
  241. <pre>',htmlspecialchars(count($_GET) ?print_r($_GET,true):'no GET'),'</pre>
  242. <strong>Input: POST</strong>
  243. <pre>',htmlspecialchars(count($_POST) ?print_r($_POST,true):'no POST'),'</pre>
  244. <strong>Input: FILE</strong>
  245. <pre>',htmlspecialchars(isset($_FILES) ?print_r($_FILES,true):'no files received'),'</pre>
  246. <strong>Input: COOKIE</strong>
  247. <pre>',htmlspecialchars(count($_COOKIE) ?print_r($_COOKIE,true):'no coockies'),'</pre>
  248. <strong>Input: Included files</strong>
  249. <pre>',print_r(get_included_files(),true),'</pre>
  250. </div>';
  251.  
  252. }
  253.  
  254. /**
  255. * renvoie la pile d'appel purgée des appels internes dans la classe.
  256. * @static
  257. * @uses Debug::ignoreDebugCall()
  258. * @return array
  259. */
  260. static public function debug_backtrace()
  261. {
  262. self::ignoreDebugCall($x);
  263. return $x;
  264. }
  265.  
  266. /***
  267. * renvoie une chaine formatée en xhtml qui contient le nom de la
  268. * fonction dans la pile d'appel à la profondeur passée en paramettre.
  269. * attention, cette pile est dépourvue des appels internes à la classe.
  270. * @static
  271. * @access public
  272. * @param integer $i (optionnel) profondeur supplementaire
  273. * @uses Debug::printCaller()
  274. * @return string
  275. */
  276. static public function getCaller($i = 0)
  277. {
  278. self::printCaller($i);
  279. return ob_get_clean();
  280. }
  281.  
  282. /**
  283. * revoie une pile formatée en xhtml pour affichage
  284. * @static
  285. * @access private
  286. * @param boolean $full
  287. * @uses Debug::$inhibit
  288. * @uses Debug::ignoreDebugCall()
  289. * @uses Debug::printStackLine()
  290. * @uses Debug::var_dump()
  291. **/
  292. static function getStack( $full = false)
  293. {
  294. if ( self::$inhibit ) return ;
  295.  
  296. $tab = debug_backtrace();
  297. self::ignoreDebugCall($tab);
  298.  
  299. // ($tab);
  300. if ( self::$outputHTML )
  301. {
  302. echo "<ol class=\"debugStack\">\n";
  303. }
  304. foreach( $tab as $y => $x )
  305. {
  306. //on se moque pas mal des appels à l'intérieur de la classe
  307. //Ceci dit c'est + pratique de tester le fichier que la classe.
  308. echo self::$outputHTML?'<li>':"\t";
  309. self::printStackLine($x);
  310. if ( $full )
  311. {
  312. self::var_dump($x, false);
  313. }
  314. echo self::$outputHTML?'</li>':"\n";
  315. }
  316. if ( self::$outputHTML )
  317. {
  318. echo "</ol>\n";
  319. }
  320. return ob_get_clean();
  321. }
  322.  
  323. /**
  324. * affiche immédiatement (en option ou pas) ou est le script en
  325. * s'affranchissant des éventuels tampons de capture de sortie
  326. * @static
  327. * @param mixed $msg affiche le contenu d'une variable (avec le type, via serialize)
  328. * @param boolean $unloadBuffer si vrai s'affranchir des ob_start
  329. * @uses Debug::unloadOutBuffer()
  330. * @uses Debug::printStackLine()
  331. * @uses Debug::reloadOutBuffer()
  332. * @return void
  333. * */
  334. static public function here( $msg = null, $unloadBuffer = true )
  335. {
  336. if ( self::$inhibit ) return ;
  337.  
  338. if ( $unloadBuffer ) $buffer = self::unloadOutBuffer();
  339. $tab = debug_backtrace();
  340. self::printNewLine();
  341. self::printStackLine($tab[0]);
  342. echo ' param = ',serialize($msg);
  343. self::printNewLine();
  344. if ( $unloadBuffer ) self::reloadOutBuffer($buffer);
  345. }
  346.  
  347. static protected function printNewLine()
  348. {
  349. echo self::$outputHTML ?'<br/>':"\n";
  350. }
  351.  
  352.  
  353. /**
  354. * enlève les appels interne à à la pile d'un bactrace
  355. * @static
  356. * @access protected
  357. * @param array $tab
  358. * @return void
  359. * */
  360. static protected function ignoreDebugCall(&$tab )
  361. {
  362. while (
  363. ( isset($tab[1], $tab[0]['file']) and $tab[0]['file'] === __FILE__ )
  364. or
  365. ( !isset($tab[0]['file']) and isset($tab[1]['file']) ) ) // le cas du serialize
  366. {
  367. array_shift($tab);
  368. }
  369. }
  370.  
  371. /**
  372. * affiche la ligne et le fichier responsable de l'appel à cette fonction
  373. * @static
  374. * @param integer $i profondeur supplémentaire, si trop grand l'appel du bas de la pile
  375. * @uses Debug::ignoreDebugCall()
  376. * @uses Debug::printStackLine()
  377. * @uses self::$inhibit()
  378. * return void
  379. * */
  380. static public function printCaller($i = 0)
  381. {
  382. if ( self::$inhibit ) return ;
  383. $tab = debug_backtrace();
  384. self::ignoreDebugCall($tab);
  385.  
  386. if ( isset( $tab[$i] ) )
  387. {
  388. self::printStackLine($tab[$i]);
  389. }
  390. else
  391. {
  392. self::printStackLine(end($tab));
  393. }
  394. }
  395.  
  396. function printSimpleBackTrace($full = false)
  397. {
  398. if ( self::$inhibit ) return ;
  399. $tab = debug_backtrace();
  400. self::ignoreDebugCall($tab);
  401. foreach( $tab as $tmp )
  402. {
  403. foreach( $tmp as $k => $v )
  404. {
  405. echo " ",$k,'=>';
  406. if ( !$full and $k !== 'object' )
  407. {
  408. echo $v;
  409. }
  410. else
  411. {
  412. echo gettype($v);
  413. }
  414. }
  415. self::printNewLine();
  416. }
  417. }
  418.  
  419. /***
  420. * affiche une exception en html, css embeded
  421. * @static
  422. * @uses Debug::printExceptionHTML()
  423. * @uses Debug::printExceptionTXT()
  424. * @uses Debug::$inhibit
  425. * @return void
  426. * */
  427. static public function printException(Exception $e)
  428. {
  429. if ( self::$inhibit ) return ;
  430. self::$outputHTML?printExceptionHTML($e):printExceptionTXT($e);
  431. }
  432.  
  433. /***
  434. * affiche une exception en html, css embeded
  435. * @static
  436. * @uses Debug::printStackLinkHTML()
  437. * @uses Exception::getFile()
  438. * @uses Exception::getLine()
  439. * @uses Exception::getTraceAsString()
  440. * @return void
  441. * */
  442. static protected function printExceptionHTML(&$e)
  443. {
  444. echo '
  445. <pre style="color:red" class="debugStack">
  446. <b>',get_class($e),':</b>', $e->getMessage(),'
  447. Exception lancée dans';
  448. self::printStackLinkHTML( $e->getFile(), $e->getLine() );
  449. echo "\n\t",str_replace("\n","\n\t",$e->getTraceAsString()),
  450. '</pre>';
  451. }
  452.  
  453. /***
  454. * affiche une exception en html, css embeded
  455. * @static
  456. * @uses Exception::getFile()
  457. * @uses Exception::getLine()
  458. * @uses Exception::getTraceAsString()
  459. * @return void
  460. * */
  461. static protected function printExceptionTXT(&$e)
  462. {
  463. echo '
  464. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  465. ',get_class($e),': ', $e->getMessage(),'
  466. Exception lancée dans', $e->getFile(),':', $e->getLine(),'
  467. ',str_replace("\n","\n\t",$e->getTraceAsString()),'
  468. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
  469. ';
  470. }
  471.  
  472.  
  473.  
  474.  
  475.  
  476.  
  477.  
  478. /***
  479. * affiche l'état de la pile dans le flux, utilise des css du site.
  480. * @static
  481. * @access public
  482. * @return void
  483. * @uses Debug::$inhibit
  484. * @uses Debug::getStack()
  485. * */
  486. static public function printStack($full = false)
  487. {
  488. if ( self::$inhibit ) return ;
  489. echo self::getStack($full);
  490. }
  491.  
  492. /**
  493. * affiche une ligne de pile d'appel
  494. * @param array $x une ligne de backtrace
  495. * @access protected
  496. * @static
  497. * @return void
  498. * @uses Debug::printStackLinkHTMLHTML()
  499. * @uses Debug::printStackLineTXT()
  500. * */
  501. static protected function printStackLine($x)
  502. {
  503. if ( self::$outputHTML )
  504. {
  505. self::printStackLineHTML($x);
  506. }
  507. else
  508. {
  509. self::printStackLineTXT($x);
  510. }
  511. }
  512.  
  513. static protected function printStackLineHTML($x)
  514. {
  515. if ( isset($x['class']) )
  516. {
  517. $class = $x['class'].$x['type'];
  518. }
  519. else
  520. {
  521. $class = null;
  522. }
  523. if ( isset( $x['file'] ) )
  524. {
  525. echo '<b>',$class,$x['function'],'</b> appelé en ';
  526. self::printStackLinkHTML($x['file'], $x['line']);
  527. }
  528. else if ( isset( $x['args'] ) )
  529. {
  530. echo '<b>',$class,$x['function'],'</b> appelé en callback';
  531. if ( isset($x['args'][0],$x['args'][1]) )
  532. {
  533. echo ' depuis ';
  534. self::printStackLinkHTML(
  535. $x['args'][0],
  536. $x['args'][1]);
  537. }
  538. }
  539. else
  540. {
  541. echo '<b>',$class,$x['function'],'</b>';
  542. }
  543. echo ' ( OB:',ob_get_level(),' )';
  544. return true;
  545. }
  546.  
  547.  
  548. static protected function printStackLineTXT($x)
  549. {
  550. if ( isset($x['class']) )
  551. {
  552. $class = $x['class'].$x['type'];
  553. }
  554. else
  555. {
  556. $class = null;
  557. }
  558. if ( isset( $x['file'] ) )
  559. {
  560. echo $class,$x['function'],' appelé en ',$x['file'],':',$x['line'];
  561. }
  562. else if ( isset( $x['args'] ) )
  563. {
  564. echo $class,$x['function'],' appelé en callback';
  565. if ( isset($x['args'][0],$x['args'][1]) )
  566. {
  567. echo ' depuis ',$x['args'][0],':',$x['args'][1];
  568. }
  569. }
  570. else
  571. {
  572. echo $class,$x['function'];
  573. }
  574. echo ' ( OB:',ob_get_level(),' ) ';
  575. return true;
  576. }
  577.  
  578.  
  579.  
  580.  
  581.  
  582.  
  583. /**
  584. * cree le p'tit lien dans la pile pour aller vers ma doc sur BddSql
  585. * @access protected
  586. * @static
  587. * @uses Debug::uri2url()
  588. * @uses SourceCode::$param
  589. * @param filename $file
  590. * @param integer $line
  591. * @return void
  592. * */
  593. static protected function printStackLinkHTML($file, $line)
  594. {
  595. echo '<a href="',self::uri2url($file),'?',SourceCode::$param,
  596. '#line',$line,'" title="voir le code">',$file,'</a>:',$line;
  597. }
  598.  
  599. /**
  600. * recrée une pile de outputBuffer à partir d'un tableau de chaine
  601. * @static
  602. * @param $array le contenu à remettre en buffer.
  603. * @uses Debug::$inhibit
  604. * @see self::unloadOutBuffer()
  605. * */
  606. static public function reloadOutBuffer($buff)
  607. {
  608. if ( self::$inhibit ) return ;
  609.  
  610. $n = count($buff) - 1;
  611. for( $it = $n ; $it >= 0 ; $it--)
  612. {
  613. echo $buff[$it];
  614. unset($buff[$it]);
  615. }
  616. }
  617.  
  618. /**
  619. * dépile les outputbuffer vers un tableau
  620. * @static
  621. * @uses Debug::$inhibit
  622. * @return array
  623. * @see self::reloadOutBuffer()
  624. * */
  625. static public function unloadOutBuffer()
  626. {
  627. if ( self::$inhibit ) return ;
  628.  
  629. $buff = array();
  630. while( ob_get_level() > 1 )
  631. {
  632. $buff[]=ob_get_clean();
  633. }
  634. return $buff;
  635. }
  636.  
  637. /***
  638. * replace un nom de fichier local en ce qu'il devrait être sur le web
  639. * pet'te que ça marche pas.
  640. * @param filename $file
  641. * @return string
  642. * */
  643. static protected function uri2url( $file )
  644. {
  645. $hide[] = '/var/www';
  646. $hide[] = $_SERVER['DOCUMENT_ROOT'];
  647. return str_replace($hide,'http://'.$_SERVER['SERVER_NAME'], $file);
  648. }
  649.  
  650.  
  651. /***
  652.   * Affiche la définition et les valeurs d'un objet (type inconnu)
  653.   * @param $mixed $objet
  654.   * @param boolean $here
  655.   * @uses Debug::ignoreDebugCall()
  656.   * @uses Debug::printStackLine(
  657.   * */
  658. static public function var_dump ($objet, $here = true)
  659. {
  660. if ( self::$inhibit) return;
  661. var_dump($objet);
  662. $dump = ob_get_clean();
  663. if ( self::$outputHTML )
  664. {
  665. echo '<pre style="background-color:WhiteSmoke;color:gray">';
  666. }
  667. if ( $here )
  668. {
  669. self::ignoreDebugCall($x);
  670. self::printStackLine($x[0]);
  671. }
  672. echo "\n";
  673. if ( self::$outputHTML )
  674. {
  675. echo htmlspecialchars($dump),
  676. '</pre>';
  677. }
  678. }
  679.  
  680.  
  681. /***
  682. * affiche les stats d'utilisation de la mémoire.
  683. * */
  684. static public function printMemoryUsage()
  685. {
  686. //Let's do some exotic piece of code...
  687. function calculerTailleUniteOctets($taille)
  688. {
  689. if ( $taille < 1024 )
  690. {
  691. return $taille.' O';
  692. }
  693. else if ( $taille < 1048576 )
  694. {
  695. return round($taille/1024.0 , 1).' Ko';
  696. }
  697. else if ( $taille < 1073741824 /*2^30*/ )
  698. {
  699. return round($taille/ 1048576.0 , 1).' Mo';
  700. }
  701. else if ( $taille < 1099511627776 )
  702. {
  703. return round($taille/1073741824.0 , 1).' Go';
  704. }
  705. else //1125899906842624
  706. {
  707. return round($taille/1099511627776.0 , 1).' To';
  708. }
  709. }
  710.  
  711. if ( self::$inhibit ) return ;
  712. global $start_time;
  713.  
  714. echo ( self::$outputHTML )?'
  715. <pre style="background-color:WhiteSmoke;color:gray">
  716. ':'
  717. ------------------------------------------------------------------------
  718. ';
  719.  
  720. echo
  721. 'memory usage (current): ',$n,' - ',calculerTailleUniteOctets($n),"\n",
  722. 'memory usage (peak): ',$m,' - ',calculerTailleUniteOctets($m),"\n",
  723. 'memory max allowed: ',ini_get('memory_limit'),"\n",
  724. 'execution time: ',round(microtime(true) - $start_time, 5)," s \n",
  725. 'execution time allowed: ',ini_get('max_execution_time')," s \n";
  726.  
  727. echo self::$outputHTML ? '
  728. </pre>
  729. ':'
  730. ------------------------------------------------------------------------
  731. ';
  732. }
  733.  
  734.  
  735.  
  736.  
  737. /**
  738. * @param string $action
  739. * */
  740. protected function writeLog($action, $option = null)
  741. {
  742. if ( is_resource($this->fp) )
  743. {
  744. fwrite( $this->fp, $this->uid."\t".$action."\t".strip_tags(self::getCaller(0))."\t".$option."\n" );
  745. fflush( $this->fp );
  746. }
  747. }
  748.  
  749. }
  750. Debug::$debug_outup = 'DEBUG_ARRAY.log';
  751. Debug::$inhibit = false;


Poster une réponse Retrouver la discussion sur le forum

Avatar de gene69 gene69
Membre Expert
le 18/08/2011
ligne 600 vous lisez "SourceCode::$param" c'est une classe publiée ici.

il y a une démo ici.


Developpez.com décline toute responsabilité quant à l'utilisation des différents éléments téléchargés.

Connexion

Identifiant
Mot de passe
S'inscrireMot de passe oublié ?
 
 
 
 
Partenaires

Hébergement Web