Skip to content

Instantly share code, notes, and snippets.

@ondrejmirtes
Created March 18, 2011 12:44
Show Gist options
  • Save ondrejmirtes/875999 to your computer and use it in GitHub Desktop.
Save ondrejmirtes/875999 to your computer and use it in GitHub Desktop.
PHP Nette CLI comfortable debugging
<?php
namespace Tools;
use Nette\Debug;
use Nette\Environment;
use Nette\Finder;
/**
* Shows exceptions thrown in CLI mode in browser.
* @author Ondřej Mirtes
*/
class ConsoleDebug extends \Nette\Object
{
/**
* @var bool
*/
private static $enabled = FALSE;
/**
* @var string
*/
private static $browser;
/**
* @var string
*/
private static $catchOnly;
/**
* @var bool
*/
private static $alreadyShowed = FALSE;
public function __construct()
{
throw new \LogicException('Can not instantiate static class.');
}
/**
* @param string Browser CLI command with %s placeholder for log file path
* @param string Catches only exception of given type
*/
public static function enable($browser, $catchOnly = NULL)
{
self::$browser = $browser;
self::$catchOnly = $catchOnly;
Debug::$onFatalError[] = array(__CLASS__, '_exceptionHandler');
self::$enabled = TRUE;
}
public static function _exceptionHandler(\Exception $exception)
{
if (!self::$enabled || self::$alreadyShowed) {
return;
}
$class = get_class($exception);
if (Environment::isConsole()
&& (self::$catchOnly == NULL
|| $class == 'FatalErrorException'
|| $class == self::$catchOnly)
) {
try {
Debug::log($exception);
$hash = md5($exception);
foreach (new \DirectoryIterator(Debug::$logDirectory) as $entry) {
if (strpos($entry, $hash)) {
$file = (string) $entry;
break;
}
}
if (isset($file)) {
exec(sprintf(self::$browser, escapeshellarg('file://' . Debug::$logDirectory . '/' . $file)));
self::$alreadyShowed = TRUE;
}
} catch (\Exception $e) {
echo $e->getMessage();
return NULL;
}
}
}
}
<?php
use Tools\ConsoleDebug;
/**
* Base class for all tests.
*/
abstract class TestCase extends PHPUnit_Framework_TestCase
{
public function runBare()
{
try {
return parent::runBare();
} catch (\Exception $e) {
if (!($e instanceof \PHPUnit_Framework_AssertionFailedError)) {
ConsoleDebug::_exceptionHandler($e);
}
throw $e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment