Completed
Push — add/cloudflare_analytics ( ff2536 )
by
unknown
353:51 queued 344:18
created

WP_Cloudflare_Analytics   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
dl 0
loc 66
rs 10
c 0
b 0
f 0
wmc 8
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A get_instance() 0 7 2
A insert_code() 0 15 4
A render_code() 0 11 1
1
<?php
2
/**
3
 * Module Name: Cloudflare Analytics
4
 * Module Description: Let WPCOM users automatically insert a Cloudflare analytics JS snippet into their site header.
5
 * Requires Connection: Yes
6
 * Auto Activate: No
7
 *
8
 * @package automattic/jetpack
9
 */
10
11
/**
12
 * Bail if accessed directly
13
 */
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
/**
19
 * WP_Cloudflare_Analytics class.
20
 */
21
class WP_Cloudflare_Analytics {
22
23
	/**
24
	 * Manages the insertion of Cloudflare analytics snippets into a user's
25
	 * site <head>.
26
	 *
27
	 * @var WP_Cloudflare_Analytics Static property to hold our singleton instance
28
	 */
29
	private static $instance = false;
30
31
	/**
32
	 * Constructor method
33
	 * Causes Cloudflare JS snippet to be included during head rendering.
34
	 */
35
	public function __construct() {
36
		add_action( 'wp_head', array( $this, 'insert_code' ), 999 );
37
	}
38
39
	/**
40
	 * Function to instantiate our class and make it a singleton
41
	 */
42
	public static function get_instance() {
43
		if ( ! self::$instance ) {
44
			self::$instance = new self();
45
		}
46
47
		return self::$instance;
48
	}
49
50
	/**
51
	 * This injects Cloudflare analytics code into the footer of the page.
52
	 * Called exclusively by wp_head action
53
	 */
54
	public function insert_code() {
55
		$option      = get_option( 'cloudflare_analytics' );
56
		$tracking_id = isset( $option['code'] ) ? $option['code'] : '';
57
		if ( empty( $tracking_id ) ) {
58
			echo "<!-- Your Cloudflare Analytics Plugin is missing the tracking ID -->\r\n";
59
			return;
60
		}
61
62
		// If we're in the admin_area, return without inserting code.
63
		if ( is_admin() ) {
64
			return;
65
		}
66
67
		$this->render_code( $tracking_id );
68
	}
69
70
	/**
71
	 * Renders Cloudflare analytics code snippet.
72
	 *
73
	 * @param string $tracking_id Cloudflare Analytics tracking ID.
74
	 */
75
	private function render_code( $tracking_id ) {
76
		printf(
77
			"<!-- Cloudflare Web Analytics -->
78
            <script defer
79
                src='https://static.cloudflareinsights.com/beacon.min.js'
80
                data-cf-beacon='{\"token\": \"%s\"}'>
81
            </script>
82
            <!-- End Cloudflare Web Analytics -->\r\n",
83
			esc_html( $tracking_id )
84
		);
85
	}
86
}
87