Completed
Push — add/magic-link-for-mobile ( a67c5b...4ebb52 )
by
unknown
13:24 queued 06:01
created

Tracking   A

Complexity

Total Complexity 24

Size/Duplication

Total Lines 152
Duplicated Lines 30.26 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 24
lcom 1
cbo 4
dl 46
loc 152
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B record_user_event() 0 21 7
A tracks_record_event() 15 15 4
A tracks_build_event_obj() 24 24 4
B tracks_get_identity() 0 39 7
A enqueue_tracks_scripts() 7 11 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * Nosara Tracks for Jetpack
4
 *
5
 * @package jetpack-tracking
6
 */
7
8
namespace Automattic\Jetpack;
9
10
/**
11
 * The Tracking class, used to record events in wpcom
12
 */
13
class Tracking {
14
	private $product_name;
15
	private $connection;
16
17
	function __construct( $product_name = 'jetpack' ) {
18
		$this->product_name = $product_name;
19
		$this->connection   = new Connection\Manager();
20
	}
21
22 View Code Duplication
	function enqueue_tracks_scripts() {
23
		wp_enqueue_script( 'jptracks', plugins_url( '_inc/lib/tracks/tracks-ajax.js', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION, true );
24
		wp_localize_script(
25
			'jptracks',
26
			'jpTracksAJAX',
27
			array(
28
				'ajaxurl'            => admin_url( 'admin-ajax.php' ),
29
				'jpTracksAJAX_nonce' => wp_create_nonce( 'jp-tracks-ajax-nonce' ),
30
			)
31
		);
32
	}
33
34
	function record_user_event( $event_type, $data = array(), $user = null ) {
35
		if ( ! $user ) {
36
			$user = wp_get_current_user();
37
		}
38
		$site_url = get_option( 'siteurl' );
39
40
		$data['_via_ua']  = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
41
		$data['_via_ip']  = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
42
		$data['_lg']      = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
43
		$data['blog_url'] = $site_url;
44
		$data['blog_id']  = \Jetpack_Options::get_option( 'id' );
45
46
		// Top level events should not be namespaced
47
		if ( '_aliasUser' != $event_type ) {
48
			$event_type = $this->product_name . '_' . $event_type;
49
		}
50
51
		$data['jetpack_version'] = defined( 'JETPACK__VERSION' ) ? JETPACK__VERSION : '0';
52
53
		return $this->tracks_record_event( $user, $event_type, $data );
54
	}
55
56
	/**
57
	 * Record an event in Tracks - this is the preferred way to record events from PHP.
58
	 *
59
	 * @param mixed  $identity username, user_id, or WP_user object
0 ignored issues
show
Bug introduced by
There is no parameter named $identity. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
60
	 * @param string $event_name The name of the event
61
	 * @param array  $properties Custom properties to send with the event
62
	 * @param int    $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred
0 ignored issues
show
Documentation introduced by
Should the type for parameter $event_timestamp_millis not be false|integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
63
	 *
64
	 * @return bool true for success | \WP_Error if the event pixel could not be fired
65
	 */
66 View Code Duplication
	function tracks_record_event( $user, $event_name, $properties = array(), $event_timestamp_millis = false ) {
67
68
		// We don't want to track user events during unit tests/CI runs.
69
		if ( $user instanceof \WP_User && 'wptests_capabilities' === $user->cap_key ) {
0 ignored issues
show
Bug introduced by
The class WP_User does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
70
			return false;
71
		}
72
73
		$event_obj = $this->tracks_build_event_obj( $user, $event_name, $properties, $event_timestamp_millis );
74
75
		if ( is_wp_error( $event_obj->error ) ) {
76
			return $event_obj->error;
77
		}
78
79
		return $event_obj->record();
80
	}
81
82
	/**
83
	 * Procedurally build a Tracks Event Object.
84
	 * NOTE: Use this only when the simpler Automattic\Jetpack\Tracking->jetpack_tracks_record_event() function won't work for you.
85
	 *
86
	 * @param $identity WP_user object
87
	 * @param string                  $event_name The name of the event
88
	 * @param array                   $properties Custom properties to send with the event
89
	 * @param int                     $event_timestamp_millis The time in millis since 1970-01-01 00:00:00 when the event occurred
0 ignored issues
show
Documentation introduced by
Should the type for parameter $event_timestamp_millis not be false|integer?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
90
	 *
91
	 * @return \Jetpack_Tracks_Event|\WP_Error
92
	 */
93 View Code Duplication
	function tracks_build_event_obj( $user, $event_name, $properties = array(), $event_timestamp_millis = false ) {
94
		$identity = $this->tracks_get_identity( $user->ID );
95
96
		$properties['user_lang'] = $user->get( 'WPLANG' );
97
98
		$blog_details = array(
99
			'blog_lang' => isset( $properties['blog_lang'] ) ? $properties['blog_lang'] : get_bloginfo( 'language' ),
100
		);
101
102
		$timestamp        = ( $event_timestamp_millis !== false ) ? $event_timestamp_millis : round( microtime( true ) * 1000 );
103
		$timestamp_string = is_string( $timestamp ) ? $timestamp : number_format( $timestamp, 0, '', '' );
104
105
		return new \Jetpack_Tracks_Event(
106
			array_merge(
107
				$blog_details,
108
				(array) $properties,
109
				$identity,
110
				array(
111
					'_en' => $event_name,
112
					'_ts' => $timestamp_string,
113
				)
114
			)
115
		);
116
	}
117
118
	/**
119
	 * Get the identity to send to tracks.
120
	 *
121
	 * @param int $user_id The user id of the local user
122
	 *
123
	 * @return array $identity
124
	 */
125
	function tracks_get_identity( $user_id ) {
126
127
		// Meta is set, and user is still connected.  Use WPCOM ID
128
		$wpcom_id = get_user_meta( $user_id, 'jetpack_tracks_wpcom_id', true );
129
		if ( $wpcom_id && $this->connection->is_user_connected( $user_id ) ) {
130
			return array(
131
				'_ut' => 'wpcom:user_id',
132
				'_ui' => $wpcom_id,
133
			);
134
		}
135
136
		// User is connected, but no meta is set yet.  Use WPCOM ID and set meta.
137
		if ( $this->connection->is_user_connected( $user_id ) ) {
138
			$wpcom_user_data = $this->connection->get_connected_user_data( $user_id );
139
			update_user_meta( $user_id, 'jetpack_tracks_wpcom_id', $wpcom_user_data['ID'] );
140
141
			return array(
142
				'_ut' => 'wpcom:user_id',
143
				'_ui' => $wpcom_user_data['ID'],
144
			);
145
		}
146
147
		// User isn't linked at all.  Fall back to anonymous ID.
148
		$anon_id = get_user_meta( $user_id, 'jetpack_tracks_anon_id', true );
149
		if ( ! $anon_id ) {
150
			$anon_id = \Jetpack_Tracks_Client::get_anon_id();
151
			add_user_meta( $user_id, 'jetpack_tracks_anon_id', $anon_id, false );
152
		}
153
154
		if ( ! isset( $_COOKIE['tk_ai'] ) && ! headers_sent() ) {
155
			setcookie( 'tk_ai', $anon_id );
156
		}
157
158
		return array(
159
			'_ut' => 'anon',
160
			'_ui' => $anon_id,
161
		);
162
163
	}
164
}
165