Merge "Add .pipeline/ with dev image variant"
[lhc/web/wiklou.git] / includes / libs / Xhprof.php
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 * Convenience class for working with XHProf
23 * <https://github.com/phacility/xhprof>. XHProf can be installed as a PECL
24 * package for use with PHP5 (Zend PHP) and is built-in to HHVM 3.3.0.
25 *
26 * This also supports using the Tideways profiler
27 * <https://github.com/tideways/php-profiler-extension>, which additionally
28 * has support for PHP7.
29 *
30 * @since 1.28
31 */
32 class Xhprof {
33 /**
34 * @var bool $enabled Whether XHProf is currently running.
35 */
36 protected static $enabled;
37
38 /**
39 * Start xhprof profiler
40 * @return bool
41 */
42 public static function isEnabled() {
43 return self::$enabled;
44 }
45
46 /**
47 * Start xhprof profiler
48 * @param int $flags
49 * @param array $options
50 * @throws Exception
51 */
52 public static function enable( $flags = 0, $options = [] ) {
53 if ( self::isEnabled() ) {
54 throw new Exception( 'Profiling is already enabled.' );
55 }
56
57 $args = [ $flags ];
58 if ( $options ) {
59 $args[] = $options;
60 }
61
62 self::$enabled = true;
63 self::callAny(
64 [
65 'xhprof_enable',
66 'tideways_enable',
67 'tideways_xhprof_enable'
68 ],
69 $args
70 );
71 }
72
73 /**
74 * Stop xhprof profiler
75 *
76 * @return array|null xhprof data from the run, or null if xhprof was not running.
77 */
78 public static function disable() {
79 if ( self::isEnabled() ) {
80 self::$enabled = false;
81 return self::callAny( [
82 'xhprof_disable',
83 'tideways_disable',
84 'tideways_xhprof_disable'
85 ] );
86 } else {
87 return null;
88 }
89 }
90
91 /**
92 * Call the first available function from $functions.
93 * @param array $functions
94 * @param array $args
95 * @return mixed
96 * @throws Exception
97 */
98 protected static function callAny( array $functions, array $args = [] ) {
99 foreach ( $functions as $func ) {
100 if ( function_exists( $func ) ) {
101 return $func( ...$args );
102 }
103 }
104
105 throw new Exception( "Neither xhprof nor tideways are installed" );
106 }
107 }