Skip to content

Instantly share code, notes, and snippets.

@nook-ru
Created March 24, 2017 14:39
Show Gist options
  • Save nook-ru/66073a3e1645b4470daf018caaa05900 to your computer and use it in GitHub Desktop.
Save nook-ru/66073a3e1645b4470daf018caaa05900 to your computer and use it in GitHub Desktop.
<?php
/**
* Класс BrowserConsoleDebug
*
* Выводит отладочную информацию в консоль браузера.
*
* Может использоваться в качестве обработчика ошибок Битрикс.
*
* Для этого необходимо прописать его в /bitrix/.settings.php
* ```
* <?php
* return array(
* // ...
* 'exception_handling' => array(
* 'value' => array(
* // ...
* 'handled_errors_types' => E_ALL & ~(E_NOTICE | E_DEPRECATED | E_STRICT | E_USER_NOTICE | E_USER_DEPRECATED),
* // ...
* 'log' => array(
* 'class_name' => 'BrowserConsoleDebug',
* ),
* ),
* );
* );
* ```
*
* @method void error() error(string $message, mixed $data = null) Аналог console.error
* @method void info() info(string $message, mixed $data = null) Аналог console.info
* @method void log() log(string $message, mixed $data = null) Аналог console.log
* @method void warn() warn(string $message, mixed $data = null) Аналог console.warn
* @method void debug() debug(string $message, mixed $data = null) Аналог console.debug
*/
class BrowserConsoleDebug extends \Bitrix\Main\Diag\ExceptionHandlerLog
{
static $availableTypes = array(
self::UNCAUGHT_EXCEPTION => 'error',
self::CAUGHT_EXCEPTION => 'info',
self::IGNORED_ERROR => 'debug',
self::LOW_PRIORITY_ERROR => 'warn',
self::ASSERTION => 'log',
self::FATAL => 'error',
);
/** @var \Bitrix\Main\Page\Asset */
protected $asset;
function __construct()
{
$this->asset = \Bitrix\Main\Page\Asset::getInstance();
$this->asset->addString(
'<script type="text/javascript">' . PHP_EOL .
/// IE and other browsers w/o console
'if (!window.console) console = {};' . PHP_EOL .
'console.log = console.log || function(){};' . PHP_EOL .
'console.warn = console.warn || function(){};' . PHP_EOL .
'console.error = console.error || function(){};' . PHP_EOL .
'console.info = console.info || function(){};' . PHP_EOL .
'console.debug = console.debug || function(){};' . PHP_EOL .
'</script>',
true,
\Bitrix\Main\Page\AssetLocation::AFTER_JS_KERNEL
);
}
/**
* @param string $name
* @param mixed[] $arguments
*/
public function __call($name, $arguments)
{
call_user_func_array(array($this, 'emitToConsole'), $arguments + compact('name'));
}
public function initialize(array $options)
{
// у нас нет настроек в .settings.php
}
/** {@inheritdoc} */
public function write($exception, $logType)
{
/** @var \Error|\Exception $exception */
$file = \Bitrix\Main\IO\Path::normalize($exception->getFile());
$dr = \Bitrix\Main\IO\Path::normalize($_SERVER['DOCUMENT_ROOT']);
$file = str_replace($dr, '', $file);
$trace = explode("\n", $exception->getTraceAsString());
array_walk($trace, function (&$v)
{
$v = preg_replace('/^#\d+\s?/', '', $v);
});
$context = array(
'file' => $file,
'line' => $exception->getLine(),
'trace' => $trace,
);
$this->emitToConsole($exception->getMessage(), $context, static::$availableTypes[$logType]);
}
/**
* Вывод в консоль
*
* @param string $message Сообщение
* @param mixed $data (не обязательно) Дополнительные данные, которые нужно вывести в консоли
* @param string $type Тип сообщения (@see:static::$availableTypes)
*/
protected function emitToConsole($message, $data = null, $type = 'log')
{
if (!in_array($type, static::$availableTypes))
{
throw new InvalidArgumentException(sprintf('$type argument should be one of: %s. `%s` specified.', implode(', ', static::$availableTypes), $type));
}
ob_start();
echo '<script type="text/javascript">' . PHP_EOL . '//<![CDATA[' . PHP_EOL;
if (isset($data))
{
if (!\Bitrix\Main\Application::getInstance()->isUtfMode())
{
$data = \Bitrix\Main\Text\Encoding::convertEncoding($data, SITE_CHARSET, 'UTF-8');
}
echo 'console.' . $type . '(' . \Bitrix\Main\Web\Json::encode($message) . ', ' . json_encode($data,
JSON_PARTIAL_OUTPUT_ON_ERROR) . ');' . PHP_EOL;
}
else
{
echo 'console.' . $type . '(' . \Bitrix\Main\Web\Json::encode($message) . ');' . PHP_EOL;
}
echo '//]]>' . PHP_EOL . '</script>' . PHP_EOL;
$this->asset->addString(ob_get_clean(), false, \Bitrix\Main\Page\AssetLocation::AFTER_JS);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment