Passed
Push — master ( d979ac...b22592 )
by Fabio
05:10
created

TFirebugLogRoute::formatFirebugLogMessage()   B

Complexity

Conditions 9
Paths 36

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

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