Completed
Push — update/tracking-in-dev-mode ( 39a6d0 )
by
unknown
11:54 queued 05:04
created

Tracking   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 168
Duplicated Lines 6.55 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
dl 11
loc 168
rs 10
c 0
b 0
f 0
wmc 28
lcom 1
cbo 6

6 Methods

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

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 automattic/jetpack-tracking
6
 */
7
8
namespace Automattic\Jetpack;
9
10
use Automattic\Jetpack\Status;
11
12
/**
13
 * The Tracking class, used to record events in wpcom
14
 */
15
class Tracking {
16
	private $product_name;
17
	private $connection;
18
19
	/**
20
	 * Creates the Tracking object.
21
	 *
22
	 * @param String                                $product_name the slug of the product that we are tracking.
23
	 * @param Automattic\Jetpack\Connection\Manager $connection   the connection manager object.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $connection not be Automattic\Jetpack\Connection\Manager|null?

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...
24
	 */
25
	function __construct( $product_name = 'jetpack', $connection = null ) {
26
		$this->product_name = $product_name;
27
		$this->connection   = $connection;
28
		if ( is_null( $this->connection ) ) {
29
			// TODO We should always pass a Connection.
30
			$this->connection = new Connection\Manager();
31
		}
32
	}
33
34 View Code Duplication
	function enqueue_tracks_scripts() {
35
		wp_enqueue_script( 'jptracks', plugins_url( '_inc/lib/tracks/tracks-ajax.js', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION, true );
36
		wp_localize_script(
37
			'jptracks',
38
			'jpTracksAJAX',
39
			array(
40
				'ajaxurl'            => admin_url( 'admin-ajax.php' ),
41
				'jpTracksAJAX_nonce' => wp_create_nonce( 'jp-tracks-ajax-nonce' ),
42
			)
43
		);
44
	}
45
46
	function record_user_event( $event_type, $data = array(), $user = null ) {
47
		if ( ! $user ) {
48
			$user = wp_get_current_user();
49
		}
50
		$site_url = get_option( 'siteurl' );
51
52
		$data['_via_ua']  = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
53
		$data['_via_ip']  = isset( $_SERVER['REMOTE_ADDR'] ) ? $_SERVER['REMOTE_ADDR'] : '';
54
		$data['_lg']      = isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
55
		$data['blog_url'] = $site_url;
56
		$data['blog_id']  = \Jetpack_Options::get_option( 'id' );
57
58
		// Top level events should not be namespaced
59
		if ( '_aliasUser' != $event_type ) {
60
			$event_type = $this->product_name . '_' . $event_type;
61
		}
62
63
		$data['jetpack_version'] = defined( 'JETPACK__VERSION' ) ? JETPACK__VERSION : '0';
64
65
		return $this->tracks_record_event( $user, $event_type, $data );
66
	}
67
68
	/**
69
	 * Record an event in Tracks - this is the preferred way to record events from PHP.
70
	 *
71
	 * @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...
72
	 * @param string $event_name The name of the event
73
	 * @param array  $properties Custom properties to send with the event
74
	 * @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...
75
	 *
76
	 * @return bool true for success | \WP_Error if the event pixel could not be fired
77
	 */
78
	function tracks_record_event( $user, $event_name, $properties = array(), $event_timestamp_millis = false ) {
79
80
		// We don't want to track user events during unit tests/CI runs.
81
		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...
82
			return false;
83
		}
84
85
		// Don't track users who have opted our, or not agreed to the TOS, or sites in development mode
86
		$status = new Status();
87
		if ( ! \Jetpack::jetpack_tos_agreed() || ! empty( $_COOKIE['tk_opt-out'] ) || $status->is_development_mode() ) {
88
			return false;
89
		}
90
91
		$event_obj = $this->tracks_build_event_obj( $user, $event_name, $properties, $event_timestamp_millis );
92
93
		if ( is_wp_error( $event_obj->error ) ) {
94
			return $event_obj->error;
95
		}
96
97
		return $event_obj->record();
0 ignored issues
show
Bug introduced by
The method record does only exist in Jetpack_Tracks_Event, but not in WP_Error.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
98
	}
99
100
	/**
101
	 * Procedurally build a Tracks Event Object.
102
	 * NOTE: Use this only when the simpler Automattic\Jetpack\Tracking->jetpack_tracks_record_event() function won't work for you.
103
	 *
104
	 * @param $identity WP_user object
105
	 * @param string                  $event_name The name of the event
106
	 * @param array                   $properties Custom properties to send with the event
107
	 * @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...
108
	 *
109
	 * @return \Jetpack_Tracks_Event|\WP_Error
110
	 */
111
	function tracks_build_event_obj( $user, $event_name, $properties = array(), $event_timestamp_millis = false ) {
112
		$identity = $this->tracks_get_identity( $user->ID );
113
114
		$properties['user_lang'] = $user->get( 'WPLANG' );
115
116
		$blog_details = array(
117
			'blog_lang' => isset( $properties['blog_lang'] ) ? $properties['blog_lang'] : get_bloginfo( 'language' ),
118
		);
119
120
		$timestamp        = ( $event_timestamp_millis !== false ) ? $event_timestamp_millis : round( microtime( true ) * 1000 );
121
		$timestamp_string = is_string( $timestamp ) ? $timestamp : number_format( $timestamp, 0, '', '' );
122
123
		return new \Jetpack_Tracks_Event(
124
			array_merge(
125
				$blog_details,
126
				(array) $properties,
127
				$identity,
128
				array(
129
					'_en' => $event_name,
130
					'_ts' => $timestamp_string,
131
				)
132
			)
133
		);
134
	}
135
136
	/**
137
	 * Get the identity to send to tracks.
138
	 *
139
	 * @param int $user_id The user id of the local user
140
	 *
141
	 * @return array $identity
142
	 */
143
	function tracks_get_identity( $user_id ) {
144
145
		// Meta is set, and user is still connected.  Use WPCOM ID
146
		$wpcom_id = get_user_meta( $user_id, 'jetpack_tracks_wpcom_id', true );
147
		if ( $wpcom_id && $this->connection->is_user_connected( $user_id ) ) {
148
			return array(
149
				'_ut' => 'wpcom:user_id',
150
				'_ui' => $wpcom_id,
151
			);
152
		}
153
154
		// User is connected, but no meta is set yet.  Use WPCOM ID and set meta.
155
		if ( $this->connection->is_user_connected( $user_id ) ) {
156
			$wpcom_user_data = $this->connection->get_connected_user_data( $user_id );
157
			update_user_meta( $user_id, 'jetpack_tracks_wpcom_id', $wpcom_user_data['ID'] );
158
159
			return array(
160
				'_ut' => 'wpcom:user_id',
161
				'_ui' => $wpcom_user_data['ID'],
162
			);
163
		}
164
165
		// User isn't linked at all.  Fall back to anonymous ID.
166
		$anon_id = get_user_meta( $user_id, 'jetpack_tracks_anon_id', true );
167
		if ( ! $anon_id ) {
168
			$anon_id = \Jetpack_Tracks_Client::get_anon_id();
169
			add_user_meta( $user_id, 'jetpack_tracks_anon_id', $anon_id, false );
170
		}
171
172
		if ( ! isset( $_COOKIE['tk_ai'] ) && ! headers_sent() ) {
173
			setcookie( 'tk_ai', $anon_id );
174
		}
175
176
		return array(
177
			'_ut' => 'anon',
178
			'_ui' => $anon_id,
179
		);
180
181
	}
182
}
183