Completed
Branch BUG-9548-transaction-completio... (b1c41e)
by
unknown
519:42 queued 503:28
created

EEH_Debug_Tools::printr()   C

Complexity

Conditions 12
Paths 37

Size

Total Lines 33
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
dl 0
loc 33
rs 5.1612
c 1
b 0
f 1
cc 12
eloc 26
nc 37
nop 6

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php if ( ! defined('EVENT_ESPRESSO_VERSION')) {exit('No direct script access allowed');}
2
/**
3
 * Class EEH_Debug_Tools
4
 *
5
 * @package 			Event Espresso
6
 * @subpackage 	core
7
 * @author 				Brent Christensen, Michael Nelson
8
 * @since 				4.0
9
 *
10
 */
11
class EEH_Debug_Tools{
12
13
	/**
14
	 * 	instance of the EEH_Autoloader object
15
	 *	@var 	$_instance
16
	 * 	@access 	private
17
	 */
18
	private static $_instance;
19
20
	/**
21
	 * array containing the start time for the timers
22
	 */
23
	private $_start_times;
24
25
	/**
26
	 * array containing all the timer'd times, which can be outputted via show_times()
27
	 */
28
	private $_times = array();
29
30
	/**
31
	 * @var array
32
	 */
33
	protected $_memory_usage_points = array();
34
35
36
37
	/**
38
	 *	@singleton method used to instantiate class object
39
	 *	@access public
40
	 *	@return EEH_Debug_Tools
41
	 */
42
	public static function instance() {
43
		// check if class object is instantiated, and instantiated properly
44
		if ( ! self::$_instance instanceof EEH_Debug_Tools ) {
45
			self::$_instance = new self();
46
		}
47
		return self::$_instance;
48
	}
49
50
51
52
	/**
53
	 *    class constructor
54
	 *
55
	 * @access    private
56
	 * @return \EEH_Debug_Tools
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
57
	 */
58
	private function __construct() {
59
		// load Kint PHP debugging library
60
		if ( ! class_exists( 'Kint' ) &&  file_exists( EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php' )){
61
			// despite EE4 having a check for an existing copy of the Kint debugging class,
62
			// if another plugin was loaded AFTER EE4 and they did NOT perform a similar check,
63
			// then hilarity would ensue as PHP throws a "Cannot redeclare class Kint" error
64
			// so we've moved it to our test folder so that it is not included with production releases
65
			// plz use https://wordpress.org/plugins/kint-debugger/  if testing production versions of EE
66
			require_once( EE_PLUGIN_DIR_PATH . 'tests' . DS . 'kint' . DS . 'Kint.class.php' );
67
		}
68
		// if ( ! defined('DOING_AJAX') || $_REQUEST['noheader'] !== 'true' || ! isset( $_REQUEST['noheader'], $_REQUEST['TB_iframe'] ) ) {
69
			//add_action( 'shutdown', array($this,'espresso_session_footer_dump') );
70
		// }
71
		$plugin = basename( EE_PLUGIN_DIR_PATH );
72
		add_action( "activate_{$plugin}", array( 'EEH_Debug_Tools', 'ee_plugin_activation_errors' ));
73
		add_action( 'activated_plugin', array( 'EEH_Debug_Tools', 'ee_plugin_activation_errors' ));
74
		add_action( 'shutdown', array( 'EEH_Debug_Tools', 'show_db_name' ));
75
	}
76
77
78
79
	/**
80
	 * 	show_db_name
81
	 *
82
	 * 	@return void
83
	 */
84
	public static function show_db_name() {
85
		if ( ! defined( 'DOING_AJAX' ) && ( defined( 'EE_ERROR_EMAILS' ) && EE_ERROR_EMAILS )) {
86
			echo '<p style="font-size:10px;font-weight:normal;color:#E76700;margin: 1em 2em; text-align: right;">DB_NAME: '. DB_NAME .'</p>';
87
		}
88
		if ( EE_DEBUG ) {
89
			EEH_Debug_Tools::instance()->show_times();
90
		}
91
	}
92
93
94
95
	/**
96
	 * 	dump EE_Session object at bottom of page after everything else has happened
97
	 *
98
	 * 	@return void
99
	 */
100
	public function espresso_session_footer_dump() {
101
		if (
102
			( defined( 'WP_DEBUG' ) && WP_DEBUG )
103
			&& ! defined( 'DOING_AJAX' )
104
			&& class_exists( 'Kint' )
105
			&& function_exists( 'wp_get_current_user' )
106
			&& current_user_can( 'update_core' )
107
			&& class_exists( 'EE_Registry' )
108
		) {
109
			Kint::dump(  EE_Registry::instance()->SSN->id() );
110
			Kint::dump( EE_Registry::instance()->SSN );
111
			//			Kint::dump( EE_Registry::instance()->SSN->get_session_data('cart')->get_tickets() );
112
			$this->espresso_list_hooked_functions();
113
			$this->show_times();
114
		}
115
	}
116
117
118
119
	/**
120
	 *    List All Hooked Functions
121
	 *    to list all functions for a specific hook, add ee_list_hooks={hook-name} to URL
122
	 *    http://wp.smashingmagazine.com/2009/08/18/10-useful-wordpress-hook-hacks/
123
	 *
124
	 * @param string $tag
125
	 * @return void
126
	 */
127
	public function espresso_list_hooked_functions( $tag='' ){
128
		global $wp_filter;
129
		echo '<br/><br/><br/><h3>Hooked Functions</h3>';
130
		if ( $tag ) {
131
			$hook[$tag]=$wp_filter[$tag];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$hook was never initialized. Although not strictly required by PHP, it is generally a good practice to add $hook = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
132
			if ( ! is_array( $hook[$tag] )) {
133
				trigger_error( "Nothing found for '$tag' hook", E_USER_WARNING );
134
				return;
135
			}
136
			echo '<h5>For Tag: '. $tag .'</h5>';
137
		}
138
		else {
139
			$hook=$wp_filter;
140
			ksort( $hook );
141
		}
142
		foreach( $hook as $tag_name => $priorities ) {
143
			echo "<br />&gt;&gt;&gt;&gt;&gt;\t<strong>$tag_name</strong><br />";
144
			ksort( $priorities );
145
			foreach( $priorities as $priority => $function ){
146
				echo $priority;
147
				foreach( $function as $name => $properties ) {
148
					echo "\t$name<br />";
149
				}
150
			}
151
		}
152
	}
153
154
155
156
	/**
157
	 *    registered_filter_callbacks
158
	 *
159
	 * @param string $hook_name
160
	 * @return array
161
	 */
162
	public static function registered_filter_callbacks( $hook_name = '' ) {
163
		$filters = array();
164
		global $wp_filter;
165
		if ( isset( $wp_filter[ $hook_name ] ) ) {
166
			$filters[ $hook_name ] = array();
167
			foreach ( $wp_filter[ $hook_name ] as $priority => $callbacks ) {
168
				$filters[ $hook_name ][ $priority ] = array();
169
				foreach ( $callbacks as $callback ) {
170
					$filters[ $hook_name ][ $priority ][] = $callback['function'];
171
				}
172
			}
173
		}
174
		return $filters;
175
	}
176
177
178
179
	/**
180
	 * reset_times
181
	 */
182
	public function reset_times(){
183
		$this->_times = array();
184
	}
185
186
187
188
	/**
189
	 * 	start_timer
190
	 * @param null $timer_name
191
	 */
192
	public function start_timer( $timer_name = NULL ){
193
		$this->_start_times[$timer_name] = microtime( TRUE );
194
	}
195
196
197
198
	/**
199
	 * stop_timer
200
	 * @param string $timer_name
201
	 */
202
	public function stop_timer( $timer_name = '' ){
203
		$timer_name = $timer_name !== '' ? $timer_name : get_called_class();
204
		if( isset( $this->_start_times[ $timer_name ] ) ){
205
			$start_time = $this->_start_times[ $timer_name ];
206
			unset( $this->_start_times[ $timer_name ] );
207
		}else{
208
			$start_time = array_pop( $this->_start_times );
209
		}
210
		$this->_times[ $timer_name ] =  number_format( microtime( true ) - $start_time, 8 );
211
	}
212
213
214
	/**
215
	 * Measure the memory usage by PHP so far.
216
	 * @param string $label The label to show for this time eg "Start of calling Some_Class::some_function"
217
	 * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
218
	 * @return void
219
	 */
220
	public function measure_memory( $label, $output_now = false ) {
221
		$memory_used = $this->convert( memory_get_peak_usage( true ) );
222
		$this->_memory_usage_points[ $label ] = $memory_used;
223
		if( $output_now ) {
224
			echo "\r\n<br>$label : $memory_used";
225
		}
226
	}
227
228
	/**
229
	 * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
230
	 * @param int $size
231
	 * @return string
232
	 */
233
	public function convert( $size ) {
234
		$unit=array('b','kb','mb','gb','tb','pb');
235
		return @round( $size / pow( 1024, $i = floor( log( $size, 1024 ) ) ), 2 ) . ' ' . $unit[ absint( $i ) ];
236
	}
237
238
239
240
	/**
241
	 * show_times
242
	 * @param bool $output_now
243
	 * @return string
244
	 */
245
	public function show_times($output_now=true){
246
		$output = '';
247
		if ( ! empty( $this->_times )) {
248
			$total = 0;
249
			$output .= '<h2 style="margin:1em .5em 0;">Times:</h2>';
250
			$output .= '<span style="color:#9999CC; font-size:.8em; margin:0 1.5em 0;">( in milliseconds )</span><br />';
251
			foreach( $this->_times as $timer_name => $total_time ) {
252
				$output .= $this->format_time( $timer_name, $total_time );
253
				$total += $total_time;
254
			}
255
			$output .= '<br />';
256
			$output .= '<h4 style="margin:1em .5em 0;">TOTAL TIME</h4>';
257
			$output .= $this->format_time( '', $total );
258
			$output .= '<br />';
259
		}
260
		if ( ! empty( $this->_memory_usage_points )) {
261
			$output .= '<h2 style="margin:1em .5em 0;">Memory</h2>' . implode( '<br />', $this->_memory_usage_points );
262
		}
263
		if( $output_now ){
264
			echo $output;
265
			return '';
266
		}
267
		return $output;
268
	}
269
270
271
272
	/**
273
	 * @param string $timer_name
274
	 * @param float $total_time
275
	 * @return string
276
	 */
277
	public function format_time( $timer_name, $total_time ) {
278
		$total_time = $total_time * 1000;
279
		switch ( $total_time ) {
280
			case $total_time < 0.01 :
281
				$color = '#8A549A';
282
				$bold = 'normal';
283
				break;
284
			case $total_time < 0.1 :
285
				$color = '#00B1CA';
286
				$bold = 'normal';
287
				break;
288
			case $total_time < 1 :
289
				$color = '#70CC50';
290
				$bold = 'normal';
291
				break;
292
			case $total_time < 10 :
293
				$color = '#FCC600';
294
				$bold = 'bold';
295
				break;
296
			case $total_time < 100 :
297
				$color = '#E76700';
298
				$bold = 'bold';
299
				break;
300
			default :
301
				$color = '#E44064';
302
				$bold = 'bold';
303
				break;
304
		}
305
		return '<span style="min-width: 10px; margin:0 1em; color:'
306
			. $color
307
			. '; font-weight:'
308
			. $bold
309
			. '; font-size:1.2em;">'
310
			. str_pad( number_format( $total_time, 5 ), 11, '0', STR_PAD_LEFT )
311
			. '</span> '
312
			. $timer_name
313
			. '<br />';
314
	}
315
316
317
318
	/**
319
	 * 	captures plugin activation errors for debugging
320
	 *
321
	 * 	@return void
322
	 */
323
	public static function ee_plugin_activation_errors() {
324
		if ( WP_DEBUG ) {
325
			$activation_errors = ob_get_contents();
326
			if ( ! empty( $activation_errors ) ) {
327
				$activation_errors = date( 'Y-m-d H:i:s' ) . "\n" . $activation_errors;
328
			}
329
			espresso_load_required( 'EEH_File', EE_HELPERS . 'EEH_File.helper.php' );
330
			if ( class_exists( 'EEH_File' )) {
331
				try {
332
					EEH_File::ensure_file_exists_and_is_writable( EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html' );
333
					EEH_File::write_to_file( EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html', $activation_errors );
334
				} catch( EE_Error $e ){
335
					EE_Error::add_error( sprintf( __(  'The Event Espresso activation errors file could not be setup because: %s', 'event_espresso' ), $e->getMessage() ), __FILE__, __FUNCTION__, __LINE__ );
336
				}
337
			} else {
338
				// old school attempt
339
				file_put_contents( EVENT_ESPRESSO_UPLOAD_DIR . 'logs' . DS . 'espresso_plugin_activation_errors.html', $activation_errors );
340
			}
341
			$activation_errors = get_option( 'ee_plugin_activation_errors', '' ) . $activation_errors;
342
			update_option( 'ee_plugin_activation_errors', $activation_errors );
343
		}
344
	}
345
346
347
348
	/**
349
	 * This basically mimics the WordPress _doing_it_wrong() function except adds our own messaging etc.  Very useful for providing helpful messages to developers when the method of doing something has been deprecated, or we want to make sure they use something the right way.
350
	 *
351
	 * @access public
352
	 * @param  string $function The function that was called
353
	 * @param  string $message A message explaining what has been done incorrectly
354
	 * @param  string $version The version of Event Espresso where the error was added
355
	 * @param int     $error_type
356
	 * @uses trigger_error()
357
	 */
358
	public function doing_it_wrong( $function, $message, $version, $error_type = E_USER_NOTICE ) {
359
		do_action( 'AHEE__EEH_Debug_Tools__doing_it_wrong_run', $function, $message, $version);
360
		$version = $version === null ? '' : sprintf( __('(This message was added in version %s of Event Espresso.', 'event_espresso' ), $version );
361
		$error_message = sprintf( esc_html__('%1$s was called %2$sincorrectly%3$s. %4$s %5$s','event_espresso' ), $function, '<strong>', '</strong>', $message, $version );
362
363
		//don't trigger error if doing ajax, instead we'll add a transient EE_Error notice that in theory should show on the next request.
364
		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
365
			$error_message .= esc_html__( 'This is a doing_it_wrong message that was triggered during an ajax request.  The request params on this request were: ', 'event_espresso' );
366
			$error_message .= '<ul><li>';
367
			$error_message .= implode( '</li><li>', EE_Registry::instance()->REQ->params() );
368
			$error_message .= '</ul>';
369
			EE_Error::add_error( $error_message, 'debug::doing_it_wrong', $function, '42' );
370
			//now we set this on the transient so it shows up on the next request.
371
			EE_Error::get_notices( is_admin(), true );
372
		} else {
373
			trigger_error( $error_message, $error_type );
374
		}
375
	}
376
377
378
379
380
	/**
381
	 * Logger helpers
382
	 */
383
384
	/**
385
	 * debug
386
	 *
387
	 * @param string $class
388
	 * @param string $func
389
	 * @param string $line
390
	 * @param array $info
391
	 * @param bool $display_request
392
	 * @param string $debug_index
393
	 * @param string $debug_key
394
	 */
395
	public static function log( $class='', $func = '', $line = '', $info = array(), $display_request = false,  $debug_index = '', $debug_key = 'EE_DEBUG_SPCO' ) {
396
		if ( WP_DEBUG && false ) {
397
			$debug_key = $debug_key . '_' . EE_Session::instance()->id();
398
			$debug_data = get_option( $debug_key, array() );
399
			$default_data = array(
400
				$class => $func . '() : ' . $line,
401
				'REQ'  => $display_request ? $_REQUEST : '',
402
			);
403
			// don't serialize objects
404
			$info = self::strip_objects( $info );
405
			$index = ! empty( $debug_index ) ? $debug_index : 0;
406
			if ( ! isset( $debug_data[$index] ) ) {
407
				$debug_data[$index] = array();
408
			}
409
			$debug_data[$index][microtime()] = array_merge( $default_data, $info );
410
			update_option( $debug_key, $debug_data );
411
		}
412
	}
413
414
415
416
	/**
417
	 * strip_objects
418
	 *
419
	 * @param array $info
420
	 * @return array
421
	 */
422
	public static function strip_objects( $info = array() ) {
423
		foreach ( $info as $key => $value ) {
424
			if ( is_array( $value ) ) {
425
				$info[ $key ] = self::strip_objects( $value );
426 View Code Duplication
			} else if ( is_object( $value ) ) {
427
				$object_class = get_class( $value );
428
				$info[ $object_class ] = array();
429
				$info[ $object_class ][ 'ID' ] = method_exists( $value, 'ID' ) ? $value->ID() : spl_object_hash( $value );
430
				if ( method_exists( $value, 'ID' ) ) {
431
					$info[ $object_class ][ 'ID' ] = $value->ID();
432
				}
433
				if ( method_exists( $value, 'status' ) ) {
434
					$info[ $object_class ][ 'status' ] = $value->status();
435
				} else if ( method_exists( $value, 'status_ID' ) ) {
436
					$info[ $object_class ][ 'status' ] = $value->status_ID();
437
				}
438
				unset( $info[ $key ] );
439
			}
440
		}
441
		return (array)$info;
442
	}
443
444
445
446
	/**
447
	 * @param mixed  $var
448
	 * @param string $var_name
449
	 * @param string $file
450
	 * @param int    $line
451
	 * @param int    $header
452
	 * @param bool   $die
453
	 */
454
	public static function printv( $var, $var_name = '', $file = __FILE__, $line = __LINE__, $header = 5, $die = false ) {
455
		$var_name = ! $var_name ? 'string' : $var_name;
456
		$heading_tag = 'h';
457
		$heading_tag .= is_int( $header ) ? $header : 5;
458
		$var_name = ucwords( str_replace( '$', '', $var_name ) );
459
		$is_method = method_exists( $var_name, $var );
460
		$var_name = ucwords( str_replace( '_', ' ', $var_name ) );
461
		$result = '<' . $heading_tag . ' style="color:#2EA2CC; margin:25px 0 0;"><b>' . $var_name . '</b>';
462
		$result .= $is_method
463
			? '<span style="color:#999">::</span><span style="color:#E76700">' . $var . '()</span><br />'
464
			: '<span style="color:#999"> : </span><span style="color:#E76700">' . $var . '</span><br />';
465
		$result .= '<span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">' . $file;
466
		$result .= '<br />line no: ' . $line . '</span>';
467
		$result .= '</' . $heading_tag . '>';
468
		if ( $die ) {
469
			die( $result );
470
		} else {
471
			echo $result;
472
		}
473
	}
474
475
476
	/**
477
	 * @param mixed $var
478
	 * @param string $var_name
479
	 * @param string $file
480
	 * @param int $line
481
	 * @param int $header
482
	 * @param bool $die
483
	 */
484
	public static function printr( $var, $var_name = '', $file = __FILE__, $line = __LINE__, $header = 5, $die = false ) {
485
		// return;
486
		$file = str_replace( rtrim( ABSPATH, '\\/' ), '', $file );
487
		//$print_r = false;
488
		if ( is_string( $var ) ) {
489
			EEH_Debug_Tools::printv( $var, $var_name, $file, $line, $header, $die );
490
			return;
491
		} else if ( is_object( $var ) ) {
492
			$var_name = ! $var_name ? 'object' : $var_name;
493
			//$print_r = true;
494
		} else if ( is_array( $var ) ) {
495
			$var_name = ! $var_name ? 'array' : $var_name;
496
			//$print_r = true;
497
		} else if ( is_numeric( $var ) ) {
498
			$var_name = ! $var_name ? 'numeric' : $var_name;
499
		} else if ( is_null( $var ) ) {
500
			$var_name = ! $var_name ? 'null' : $var_name;
501
		}
502
		$heading_tag = 'h';
503
		$heading_tag .= is_int( $header ) ? $header : 5;
504
		$var_name = ucwords( str_replace( array( '$', '_' ), array( '', ' ' ), $var_name ) );
505
		$result = '<' . $heading_tag . ' style="color:#2EA2CC; margin:25px 0 0;"><b>' . $var_name . '</b>';
506
		$result .= '<span style="color:#999;"> : </span><span style="color:#E76700;">';
507
		$result .= '<pre style="color:#999; padding:1em; background: #fff">';
508
		$result .= var_export( $var, true );
509
		$result .= '</pre></span><br /><span style="font-size:9px;font-weight:normal;color:#666;line-height: 12px;">' . $file;
510
		$result .= '<br />line no: ' . $line . '</span></' . $heading_tag . '>';
511
		if ( $die ) {
512
			die( $result );
513
		} else {
514
			echo $result;
515
		}
516
	}
517
518
519
520
521
}
522
523
524
525
/**
526
 * borrowed from Kint Debugger
527
 * Plugin URI: http://upthemes.com/plugins/kint-debugger/
528
 */
529
if ( class_exists('Kint') && ! function_exists( 'dump_wp_query' ) ) {
530
	function dump_wp_query(){
531
		global $wp_query;
532
		d($wp_query);
533
	}
534
}
535
536
/**
537
 * borrowed from Kint Debugger
538
 * Plugin URI: http://upthemes.com/plugins/kint-debugger/
539
 */
540
if ( class_exists('Kint') && ! function_exists( 'dump_wp' ) ) {
541
	function dump_wp(){
542
		global $wp;
543
		d($wp);
544
	}
545
}
546
547
/**
548
 * borrowed from Kint Debugger
549
 * Plugin URI: http://upthemes.com/plugins/kint-debugger/
550
 */
551
if ( class_exists('Kint') && ! function_exists( 'dump_post' ) ) {
552
	function dump_post(){
553
		global $post;
554
		d($post);
555
	}
556
}
557
558