Passed
Pull Request — master (#1005)
by Fabio
28:04 queued 18:59
created

TFirebugLogRoute::processLogs()   B

Complexity

Conditions 6
Paths 9

Size

Total Lines 34
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 6
eloc 24
c 1
b 1
f 0
nc 9
nop 3
dl 0
loc 34
ccs 0
cts 28
cp 0
crap 42
rs 8.9137
1
<?php
2
3
/**
4
 * TLogRouter, TLogRoute, TFileLogRoute, TEmailLogRoute class file
5
 *
6
 * @author Qiang Xue <[email protected]>
7
 * @link https://github.com/pradosoft/prado
8
 * @license https://github.com/pradosoft/prado/blob/master/LICENSE
9
 */
10
11
namespace Prado\Util;
12
13
use Prado\Web\Javascripts\TJavaScript;
14
use Prado\Web\UI\ActiveControls\TActivePageAdapter;
15
16
/**
17
 * TFirebugLogRoute class.
18
 *
19
 * TFirebugLogRoute prints selected log messages in the firebug log console.
20
 *
21
 * {@see http://www.getfirebug.com/ FireBug Website}
22
 *
23
 * @author Enrico Stahn <[email protected]>, Christophe Boulain <[email protected]>
24
 * @since 3.1.2
25
 * @method \Prado\Web\Services\TPageService getService()
26
 */
27
class TFirebugLogRoute extends TBrowserLogRoute
28
{
29
	/**
30
	 * Logs via Firebug.
31
	 * @param array $logs list of log messages
32
	 * @param bool $final is the final flush
33
	 * @param array $meta the meta data for the logs.
34
	 */
35
	protected function processLogs(array $logs, bool $final, array $meta)
36
	{
37
		$page = $this->getService()->getRequestedPage();
38
		if (empty($logs) || $this->getApplication()->getMode() === \Prado\TApplicationMode::Performance) {
39
			return;
40
		}
41
		$even = false;
42
43
		$blocks = [['info', 'Tot Time', 'Time    ', '[Level] [Category] [Message]']];
44
		for ($i = 0, $n = count($logs); $i < $n; ++$i) {
45
			$logs[$i]['even'] = ($even = !$even);
0 ignored issues
show
introduced by
The condition $even is always false.
Loading history...
46
			$blocks[] = $this->renderMessageCallback($logs[$i]);
47
		}
48
49
		try {
50
			$blocks = TJavaScript::jsonEncode($blocks);
51
		} catch (\Exception $e) {
52
			// strip everythin not 7bit ascii
53
			$blocks = preg_replace('/[^(\x20-\x7F)]*/', '', serialize($blocks));
54
		}
55
56
		// the response has already been flushed
57
		$response = $this->getApplication()->getResponse();
58
		if ($page->getIsCallback()) {
59
			$content = $response->createHtmlWriter();
60
			$content->getWriter()->setBoundary(TActivePageAdapter::CALLBACK_DEBUG_HEADER);
61
			$content->write($blocks);
62
			$response->write($content->flush());
63
		} else {
64
			$response->write(TJavaScript::renderScriptHeader());
65
			$response->write('var blocks = ' . $blocks . ";\n");
66
			$response->write($this->renderHeader());
67
			$response->write($this->renderFooter());
68
			$response->write(TJavaScript::renderScriptFooter());
69
		}
70
	}
71
72
	protected function renderHeader()
73
	{
74
		return <<<EOD
75
			if (typeof(console) == 'object')
76
			{
77
				Prado.CallbackRequestManager.logDebug(console, blocks);
78
			EOD;
79
	}
80
81
	protected function renderMessageCallback($log)
82
	{
83
		$logfunc = $this->getFirebugLoggingFunction($log[TLogger::LOG_LEVEL]);
84
		$total = sprintf('%0.6f', $log['total']);
85
		$delta = sprintf('%0.6f', $log['delta']);
86
		$msg = trim($this->formatFirebugLogMessage($log));
87
		$msg = preg_replace('/\(line[^\)]+\)$/', '', $msg); //remove line number info
88
89
		return [$logfunc, $total, $delta, $msg];
90
	}
91
92
	protected function renderFooter()
93
	{
94
		return <<<EOD
95
				if(typeof console.groupEnd === "function")
96
					console.groupEnd();
97
			}
98
			EOD;
99
	}
100
101
	/**
102
	 * Formats a log message given different fields.
103
	 * @param array $log The log to format
104
	 * @return string formatted message
105
	 */
106
	public function formatFirebugLogMessage(array $log): string
107
	{
108
		$traces = [];
109
		if (!is_string($log[TLogger::LOG_MESSAGE])) {
110
			if ($log[TLogger::LOG_MESSAGE] instanceof \Exception || $log[TLogger::LOG_MESSAGE] instanceof \Throwable) {
111
				$log[TLogger::LOG_MESSAGE] = (string) $log[TLogger::LOG_MESSAGE];
112
			} else {
113
				$log[TLogger::LOG_MESSAGE] = \Prado\Util\TVarDumper::dump($log[TLogger::LOG_MESSAGE]);
114
			}
115
		}
116
		if (!is_string($log[TLogger::LOG_MESSAGE])) {
117
			if ($log[TLogger::LOG_MESSAGE] instanceof \Exception || $log[TLogger::LOG_MESSAGE] instanceof \Throwable) {
118
				$log[TLogger::LOG_MESSAGE] = (string) $log[TLogger::LOG_MESSAGE];
119
			} else {
120
				$log[TLogger::LOG_MESSAGE] = \Prado\Util\TVarDumper::dump($log[TLogger::LOG_MESSAGE]);
121
			}
122
		}
123
		if (isset($log[TLogger::LOG_TRACES])) {
124
			$traces = array_map(fn ($trace) => "in {$trace['file']}:{$trace['line']}", $log[TLogger::LOG_TRACES]);
125
		}
126
		return '[' . $this->getLevelName($log[TLogger::LOG_LEVEL]) . '] [' . $log[TLogger::LOG_CATEGORY] . '] ' . $log[TLogger::LOG_MESSAGE]
127
			. (empty($traces) ? '' : "\n    " . implode("\n    ", $traces));
128
	}
129
130
	protected function getFirebugLoggingFunction($level)
131
	{
132
		switch ($level) {
133
			case TLogger::PROFILE:
134
			case TLogger::PROFILE_BEGIN:
135
			case TLogger::PROFILE_END:
136
			case TLogger::DEBUG:
137
			case TLogger::INFO:
138
			case TLogger::NOTICE:
139
				return 'info';
140
			case TLogger::WARNING:
141
				return 'warn';
142
			case TLogger::ERROR:
143
			case TLogger::ALERT:
144
			case TLogger::FATAL:
145
				return 'error';
146
			default:
147
				return 'log';
148
		}
149
	}
150
}
151