Completed
Push — update/ads-header ( 49094e...d515e0 )
by
unknown
22:49 queued 14:38
created

maybe_track_purchases()   C

Complexity

Conditions 11
Paths 22

Size

Total Lines 68
Code Lines 42

Duplication

Lines 14
Ratio 20.59 %

Importance

Changes 0
Metric Value
cc 11
eloc 42
nc 22
nop 1
dl 14
loc 68
rs 5.8371
c 0
b 0
f 0

How to fix   Long Method    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
2
3
/**
4
* Jetpack_Google_Analytics_Universal hooks and and enqueues support for analytics.js
5
* https://developers.google.com/analytics/devguides/collection/analyticsjs/
6
* https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce
7
*
8
* @author allendav 
9
*/
10
11
/**
12
* Bail if accessed directly
13
*/
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
class Jetpack_Google_Analytics_Universal {
19
	public function __construct() {
20
		add_filter( 'jetpack_wga_universal_commands', array( $this, 'maybe_anonymize_ip' ) );
21
		add_filter( 'jetpack_wga_universal_commands', array( $this, 'maybe_track_purchases' ) );
22
23
		add_action( 'wp_head', array( $this, 'wp_head' ), 999999 );
24
25
		add_action( 'woocommerce_after_add_to_cart_button', array( $this, 'add_to_cart' ) );
26
		add_action( 'wp_footer', array( $this, 'loop_add_to_cart' ) );
27
		add_action( 'woocommerce_after_cart', array( $this, 'remove_from_cart' ) );
28
		add_action( 'woocommerce_after_mini_cart', array( $this, 'remove_from_cart' ) );
29
		add_filter( 'woocommerce_cart_item_remove_link', array( $this, 'remove_from_cart_attributes' ), 10, 2 );
30
		add_action( 'woocommerce_after_shop_loop_item', array( $this, 'listing_impression' ) );
31
		add_action( 'woocommerce_after_shop_loop_item', array( $this, 'listing_click' ) );
32
		add_action( 'woocommerce_after_single_product', array( $this, 'product_detail' ) );
33
		add_action( 'woocommerce_after_checkout_form', array( $this, 'checkout_process' ) );
34
35
		// we need to send a pageview command last - so we use priority 24 to add
36
		// this command's JavaScript just before wc_print_js is called (pri 25)
37
		add_action( 'wp_footer', array( $this, 'send_pageview_in_footer' ), 24 );
38
	}
39
40
	public function wp_head() {
41
		$tracking_code = Jetpack_Google_Analytics_Options::get_tracking_code();
42
		if ( empty( $tracking_code ) ) {
43
			echo "<!-- No tracking ID configured for Jetpack Google Analytics -->\r\n";
44
			return;
45
		}
46
47
		// If we're in the admin_area, return without inserting code.
48
		if ( is_admin() ) {
49
			return;
50
		}
51
52
		/**
53
		 * Allow for additional elements to be added to the universal Google Analytics queue (ga) array
54
		 *
55
		 * @since 5.6.0
56
		 *
57
		 * @param array $custom_vars Array of universal Google Analytics queue elements
58
		 */
59
		$universal_commands = apply_filters( 'jetpack_wga_universal_commands', array() );
60
61
		$async_code = "
62
			<!-- Jetpack Google Analytics -->
63
			<script>
64
				window.ga = window.ga || function(){ ( ga.q = ga.q || [] ).push( arguments ) }; ga.l=+new Date;
65
				ga( 'create', '%tracking_id%', 'auto' );
66
				ga( 'require', 'ec' );
67
				%universal_commands%
68
			</script>
69
			<script async src='https://www.google-analytics.com/analytics.js'></script>
70
			<!-- End Jetpack Google Analytics -->
71
		";
72
		$async_code = str_replace( '%tracking_id%', $tracking_code, $async_code );
73
74
		$universal_commands_string = implode( "\r\n", $universal_commands );
75
		$async_code = str_replace( '%universal_commands%', $universal_commands_string, $async_code );
76
77
		echo "$async_code\r\n";
78
	}
79
80
	public function maybe_anonymize_ip( $command_array ) {
81
		if ( Jetpack_Google_Analytics_Options::anonymize_ip_is_enabled() ) {
82
			array_push( $command_array, "ga( 'set', 'anonymizeIp', true );" );
83
		}
84
85
		return $command_array;
86
	}
87
88
	public function maybe_track_purchases( $command_array ) {
89
		global $wp;
90
91
		if ( ! Jetpack_Google_Analytics_Options::track_purchases_is_enabled() ) {
92
			return $command_array;
93
		}
94
95
		if ( ! class_exists( 'WooCommerce' ) ) {
96
			return $command_array;
97
		}
98
99
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
100
		if ( ! $minimum_woocommerce_active ) {
101
			return $command_array;
102
		}
103
104
		if ( ! is_order_received_page() ) {
105
			return $command_array;
106
		}
107
108
		$order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
109
		if ( 0 == $order_id ) {
110
			return $command_array;
111
		}
112
113
		// A 1 indicates we've already tracked this order - don't do it again
114
		if ( 1 == get_post_meta( $order_id, '_ga_tracked', true ) ) {
115
			return $command_array;
116
		}
117
118
		$order = new WC_Order( $order_id );
119
		$order_currency = $order->get_currency();
120
		$command = "ga( 'set', '&cu', '" . esc_js( $order_currency ) . "' );";
121
		array_push( $command_array, $command );
122
123
		// Order items
124
		if ( $order->get_items() ) {
125 View Code Duplication
			foreach ( $order->get_items() as $item ) {
126
				$product = $order->get_product_from_item( $item );
127
				$product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
128
129
				$item_details = array(
130
					'id' => $product_sku_or_id,
131
					'name' => $item['name'],
132
					'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
133
					'price' => $order->get_item_total( $item ),
134
					'quantity' => $item['qty'],
135
				);
136
				$command = "ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );";
137
				array_push( $command_array, $command );
138
			}
139
		}
140
141
		// Order summary
142
		$summary = array(
143
			'id' => $order->get_order_number(),
144
			'affiliation' => get_bloginfo( 'name' ),
145
			'revenue' => $order->get_total(),
146
			'tax' => $order->get_total_tax(),
147
			'shipping' => $order->get_total_shipping()
148
		);
149
		$command = "ga( 'ec:setAction', 'purchase', " . wp_json_encode( $summary ) . " );";
150
		array_push( $command_array, $command );
151
152
		update_post_meta( $order_id, '_ga_tracked', 1 );
153
154
		return $command_array;
155
	}
156
157
	public function add_to_cart() {
158
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
159
			return;
160
		}
161
162
		if ( ! is_single() ) {
163
			return;
164
		}
165
166
		global $product;
167
168
		$product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
169
		$selector = ".single_add_to_cart_button";
170
171
		wc_enqueue_js(
172
			"$( '" . esc_js( $selector ) . "' ).click( function() {
173
				var productDetails = {
174
					'id': '" . esc_js( $product_sku_or_id ) . "',
175
					'name' : '" . esc_js( $product->get_title() ) . "',
176
					'quantity': $( 'input.qty' ).val() ? $( 'input.qty' ).val() : '1',
177
				};
178
				ga( 'ec:addProduct', productDetails );
179
				ga( 'ec:setAction', 'add' );
180
				ga( 'send', 'event', 'UX', 'click', 'add to cart' );
181
			} );"
182
		);
183
	}
184
185
	public function loop_add_to_cart() {
186
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
187
			return;
188
		}
189
190
		if ( ! class_exists( 'WooCommerce' ) ) {
191
			return;
192
		}
193
194
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
195
		if ( ! $minimum_woocommerce_active ) {
196
			return;
197
		}
198
199
		$selector = ".add_to_cart_button:not(.product_type_variable, .product_type_grouped)";
200
201
		wc_enqueue_js(
202
			"$( '" . esc_js( $selector ) . "' ).click( function() {
203
				var productSku = $( this ).data( 'product_sku' );
204
				var productID = $( this ).data( 'product_id' );
205
				var productDetails = {
206
					'id': productSku ? productSku : '#' + productID,
207
					'quantity': $( this ).data( 'quantity' ),
208
				};
209
				ga( 'ec:addProduct', productDetails );
210
				ga( 'ec:setAction', 'add' );
211
				ga( 'send', 'event', 'UX', 'click', 'add to cart' );
212
			} );"
213
		);
214
	}
215
216
	public function remove_from_cart() {
217
		if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
218
			return;
219
		}
220
221
		if ( ! Jetpack_Google_Analytics_Options::track_remove_from_cart_is_enabled() ) {
222
			return;
223
		}
224
225
		// We listen at div.woocommerce because the cart 'form' contents get forcibly
226
		// updated and subsequent removals from cart would then not have this click
227
		// handler attached
228
		wc_enqueue_js(
229
			"$( 'div.woocommerce' ).on( 'click', 'a.remove', function() {
230
				var productSku = $( this ).data( 'product_sku' );
231
				var productID = $( this ).data( 'product_id' );
232
				var quantity = $( this ).parent().parent().find( '.qty' ).val()
233
				var productDetails = {
234
					'id': productSku ? productSku : '#' + productID,
235
					'quantity': quantity ? quantity : '1',
236
				};
237
				ga( 'ec:addProduct', productDetails );
238
				ga( 'ec:setAction', 'remove' );
239
				ga( 'send', 'event', 'UX', 'click', 'remove from cart' );
240
			} );"
241
		);
242
	}
243
244
	/**
245
	* Adds the product ID and SKU to the remove product link (for use by remove_from_cart above) if not present
246
	*/
247
	public function remove_from_cart_attributes( $url, $key ) {
248
		if ( false !== strpos( $url, 'data-product_id' ) ) {
249
			return $url;
250
		}
251
252
		$item = WC()->cart->get_cart_item( $key );
253
		$product = $item[ 'data' ];
254
255
		$new_attributes = sprintf( 'href="%s" data-product_id="%s" data-product_sku="%s"',
256
			esc_attr( $url ),
257
			esc_attr( $product->get_id() ),
258
			esc_attr( $product->get_sku() )
259
			);
260
		$url = str_replace( 'href=', $new_attributes );
261
		return $url;
262
	}
263
264
	public function listing_impression() {
265
		if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
266
			return;
267
		}
268
269
		if ( ! Jetpack_Google_Analytics_Options::track_product_impressions_is_enabled() ) {
270
			return;
271
		}
272
273
		if ( isset( $_GET['s'] ) ) {
274
			$list = "Search Results";
275
		} else {
276
			$list = "Product List";
277
		}
278
279
		global $product, $woocommerce_loop;
280
		$product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
281
282
		$item_details = array(
283
			'id' => $product_sku_or_id,
284
			'name' => $product->get_title(),
285
			'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
286
			'list' => $list,
287
			'position' => $woocommerce_loop['loop']
288
		);
289
		wc_enqueue_js( "ga( 'ec:addImpression', " . wp_json_encode( $item_details ) . " );" );
290
	}
291
292
	public function listing_click() {
293
		if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
294
			return;
295
		}
296
297
		if ( ! Jetpack_Google_Analytics_Options::track_product_clicks_is_enabled() ) {
298
			return;
299
		}
300
301
		if ( isset( $_GET['s'] ) ) {
302
			$list = "Search Results";
303
		} else {
304
			$list = "Product List";
305
		}
306
307
		global $product, $woocommerce_loop;
308
		$product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
309
310
		$selector = ".products .post-" . esc_js( $product->get_id() ) . " a";
311
312
		$item_details = array(
313
			'id' => $product_sku_or_id,
314
			'name' => $product->get_title(),
315
			'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
316
			'position' => $woocommerce_loop['loop']
317
		);
318
319
		wc_enqueue_js(
320
			"$( '" . esc_js( $selector ) . "' ).click( function() {
321
				if ( true === $( this ).hasClass( 'add_to_cart_button' ) ) {
322
					return;
323
				}
324
325
				ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );
326
				ga( 'ec:setAction', 'click', { list: '" . esc_js( $list ) . "' } );
327
				ga( 'send', 'event', 'UX', 'click', { list: '" . esc_js( $list ) . "' } );
328
			} );"
329
		);
330
	}
331
332
	public function product_detail() {
333
		if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
334
			return;
335
		}
336
337
		if ( ! Jetpack_Google_Analytics_Options::track_product_detail_view_is_enabled() ) {
338
			return;
339
		}
340
341
		global $product;
342
		$product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
343
344
		$item_details = array(
345
			'id' => $product_sku_or_id,
346
			'name' => $product->get_title(),
347
			'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
348
			'price' => $product->get_price()
349
		);
350
		wc_enqueue_js(
351
			"ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );" .
352
			"ga( 'ec:setAction', 'detail' );"
353
		);
354
	}
355
356
	public function checkout_process() {
357
		if ( ! Jetpack_Google_Analytics_Options::enhanced_ecommerce_tracking_is_enabled() ) {
358
			return;
359
		}
360
361
		if ( ! Jetpack_Google_Analytics_Options::track_checkout_started_is_enabled() ) {
362
			return;
363
		}
364
365
		$universal_commands = array();
366
		$cart = WC()->cart->get_cart();
367
368 View Code Duplication
		foreach ( $cart as $cart_item_key => $cart_item ) {
369
			/**
370
			* This filter is already documented in woocommerce/templates/cart/cart.php
371
			*/
372
			$product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key );
373
			$product_sku_or_id = Jetpack_Google_Analytics_Utils::get_product_sku_or_id( $product );
374
375
			$item_details = array(
376
				'id' => $product_sku_or_id,
377
				'name' => $product->get_title(),
378
				'category' => Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
379
				'price' => $product->get_price(),
380
				'quantity' => $cart_item[ 'quantity' ]
381
			);
382
383
			array_push( $universal_commands, "ga( 'ec:addProduct', " . wp_json_encode( $item_details ) . " );" );
384
		}
385
386
		array_push( $universal_commands, "ga( 'ec:setAction','checkout' );" );
387
388
		wc_enqueue_js( implode( "\r\n", $universal_commands ) );
389
	}
390
391
	public function send_pageview_in_footer() {
392
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
393
			return;
394
		}
395
396
		if ( is_admin() ) {
397
			return;
398
		}
399
400
		wc_enqueue_js( "ga( 'send', 'pageview' );" );
401
	}
402
}