1<?php
2/**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 */
20
21/**
22 * Adds profiler output to the HTTP response.
23 *
24 * The least sophisticated profiler output class possible, view source! :)
25 *
26 * @ingroup Profiler
27 * @since 1.25
28 */
29class ProfilerOutputText extends ProfilerOutput {
30	/** @var float Min real time display threshold */
31	private $thresholdMs;
32
33	/** @var bool Whether to use visible text or a comment (for HTML responses) */
34	private $visible;
35
36	public function __construct( Profiler $collector, array $params ) {
37		parent::__construct( $collector, $params );
38		$this->thresholdMs = $params['thresholdMs'] ?? 1.0;
39		$this->visible = $params['visible'] ?? false;
40	}
41
42	public function logsToOutput() {
43		return true;
44	}
45
46	public function log( array $stats ) {
47		$out = '';
48
49		// Filter out really tiny entries
50		$min = $this->thresholdMs;
51		$stats = array_filter( $stats, function ( $a ) use ( $min ) {
52			return $a['real'] > $min;
53		} );
54		// Sort descending by time elapsed
55		usort( $stats, function ( $a, $b ) {
56			return $b['real'] <=> $a['real'];
57		} );
58
59		array_walk( $stats,
60			function ( $item ) use ( &$out ) {
61				$out .= sprintf( "%6.2f%% %3.3f %6d - %s\n",
62					$item['%real'], $item['real'], $item['calls'], $item['name'] );
63			}
64		);
65
66		$contentType = $this->collector->getContentType();
67		if ( wfIsCLI() ) {
68			print "<!--\n{$out}\n-->\n";
69		} elseif ( $contentType === 'text/html' ) {
70			if ( $this->visible ) {
71				print "<pre>{$out}</pre>";
72			} else {
73				print "<!--\n{$out}\n-->\n";
74			}
75		} elseif ( $contentType === 'text/javascript' || $contentType === 'text/css' ) {
76			print "\n/*\n{$out}*/\n";
77		}
78	}
79}
80