Completed
Push — try/track-potential-search-per... ( f671c9...a4e0e0 )
by
unknown
41:11 queued 32:52
created

log_mysql_query()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
class Jetpack_Search_Performance_Logger {
4
	/**
5
	 * @var Jetpack_Search_Performance_Logger
6
	 **/
7
	private static $instance = null;
8
9
	private $current_query = null;
10
	private $query_started = null;
11
	private $stats = null;
12
13
	static function init() {
14
		if ( is_null( self::$instance ) ) {
15
			self::$instance = new Jetpack_Search_Performance_Logger;
16
		}
17
18
		return self::$instance;
19
	}
20
21
	private function __construct() {
22
		$this->stats = array();
23
		// add_filter( 'jetpack_search_should_handle_query', '__return_false' );
24
		add_action( 'pre_get_posts', array( $this, 'begin_log_query' ), 10, 1 );
25
		add_action( 'did_jetpack_search_query', array( $this, 'log_jetpack_search_query' ) );
26
		add_filter( 'found_posts', array( $this, 'log_mysql_query' ), 10, 2 );
27
		add_action( 'wp_footer', array( $this, 'print_stats' ) );
28
	}
29
30
	public function begin_log_query( $query  ) {
31
		if ( $this->should_log_query( $query ) ) {
32
			$this->query_started = microtime( true );
33
			$this->current_query = $query;
34
		}
35
	}
36
37
	public function log_mysql_query( $found_posts, $query ) {
38
		if ( $this->current_query === $query ) {
39
			$duration = microtime( true ) - $this->query_started;
40
			$this->record_query_time( $duration, false );
41
			$this->reset_query_state();
42
		}
43
44
		return $found_posts;
45
	}
46
47
	public function log_jetpack_search_query() {
48
		$duration = microtime( true ) - $this->query_started;
49
		$this->record_query_time( $duration, true );
50
		$this->reset_query_state();
51
	}
52
53
	private function reset_query_state() {
54
		$this->query_started = null;
55
		$this->current_query = null;
56
	}
57
58
	private function should_log_query( $query ) {
59
		return $query->is_main_query() && $query->is_search();
60
	}
61
62
	private function record_query_time( $duration, $was_jetpack_search ) {
63
		$this->stats[] = array( $was_jetpack_search, $duration * 1000 );
64
	}
65
66
	public function print_stats() {
67
		$beacons = array();
68
		if ( ! empty( $this->stats ) ) {
69
			foreach( $this->stats as $stat ) {
70
				$search_type = $stat[0] ? 'es' : 'mysql';
71
				$beacons[] = "jetpack.search.{$search_type}.duration:{$stat[1]}|ms";
72
			}
73
		}
74
		$encoded_json = urlencode( json_encode( array( 'beacons' => $beacons ) ) );
75
		$encoded_site_url = urlencode( site_url() );
76
		$url = "https://pixel.wp.com/boom.gif?v=0.9&u={$encoded_site_url}&json={$encoded_json}";
77
		echo '<img src="' . esc_url( $url ) . '" width="1" height="1" style="display:none;" />';
78
	}
79
}