Test Failed
Push — master ( 4cd501...1b9ce5 )
by Stiofan
07:38
created

google_analytics.php ➔ geodir_getGoogleAnalytics()   D

Complexity

Conditions 16
Paths 28

Size

Total Lines 81
Code Lines 50

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 272

Importance

Changes 0
Metric Value
cc 16
eloc 50
nc 28
nop 3
dl 0
loc 81
rs 4.9906
c 0
b 0
f 0
ccs 0
cts 57
cp 0
crap 272

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
 * Google analystics related functions.
4
 *
5
 * @since 1.0.0
6
 * @package GeoDirectory
7
 */
8
9
/**
10
 * Formats seconds into to h:m:s.
11
 *
12
 * @since 1.0.0
13
 *
14
 * @param int  $sec The number of seconds.
15
 * @param bool $padHours Whether add leading zero for less than 10 hours. Default false.
16
 * @return string h:m:s format.
17
 */
18
function geodir_sec2hms($sec, $padHours = false)
19
{
20
    // holds formatted string
21
    $hms = "";
22
    // there are 3600 seconds in an hour, so if we
23
    // divide total seconds by 3600 and throw away
24
    // the remainder, we've got the number of hours
25
    $hours = intval(intval($sec) / 3600);
26
27
    // add to $hms, with a leading 0 if asked for
28
    $hms .= ($padHours) ? str_pad($hours, 2, "0", STR_PAD_LEFT) . ':' : $hours . ':';
29
30
    // dividing the total seconds by 60 will give us
31
    // the number of minutes, but we're interested in
32
    // minutes past the hour: to get that, we need to
33
    // divide by 60 again and keep the remainder
34
    $minutes = intval(($sec / 60) % 60);
35
36
    // then add to $hms (with a leading 0 if needed)
37
    $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT) . ':';
38
39
    // seconds are simple - just divide the total
40
    // seconds by 60 and keep the remainder
41
    $seconds = intval($sec % 60);
42
43
    // add to $hms, again with a leading 0 if needed
44
    $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
45
46
    // done!
47
    return $hms;
48
}
49
50
/**
51
 * Get the google analytics via api.
52
 *
53
 * @since 1.0.0
54
 *
55
 * @param string $page Page url to use in analytics filters.
56
 * @param bool   $ga_start The start date of the data to include in YYYY-MM-DD format.
57
 * @param bool   $ga_end The end date of the data to include in YYYY-MM-DD format.
58
 * @return string Html text content.
59
 */
60
function geodir_getGoogleAnalytics($page, $ga_start, $ga_end)
0 ignored issues
show
Unused Code introduced by
The parameter $ga_start is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $ga_end is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
61
{
62
63
    // NEW ANALYTICS
64
65
    $start_date = '';
66
    $end_date = '';
67
    $dimensions = '';
68
    $sort = '';
69
    $filters = "ga:pagePath==".$page;
70
    $metrics = "ga:pageviews";
71
    $realtime = false;
72
    $limit = false;
73
    if(isset($_REQUEST['ga_type']) && $_REQUEST['ga_type']=='thisweek'){
74
        $start_date = date('Y-m-d', strtotime("-6 day"));
75
        $end_date = date('Y-m-d');
76
        $dimensions = "ga:date,ga:nthDay";
77
    }elseif(isset($_REQUEST['ga_type']) && $_REQUEST['ga_type']=='lastweek'){
78
        $start_date = date('Y-m-d', strtotime("-13 day"));
79
        $end_date = date('Y-m-d', strtotime("-7 day"));
80
        $dimensions = "ga:date,ga:nthDay";
81
    }
82
    elseif(isset($_REQUEST['ga_type']) && $_REQUEST['ga_type']=='thisyear'){
83
        $start_date = date('Y')."-01-01";
84
        $end_date = date('Y-m-d');
85
        $dimensions = "ga:month,ga:nthMonth";
86
    }
87
    elseif(isset($_REQUEST['ga_type']) && $_REQUEST['ga_type']=='lastyear'){
88
        $start_date = date('Y', strtotime("-1 year"))."-01-01";
89
        $end_date = date('Y', strtotime("-1 year"))."-12-31";
90
        $dimensions = "ga:month,ga:nthMonth";
91
    }
92
    elseif(isset($_REQUEST['ga_type']) && $_REQUEST['ga_type']=='country'){
93
        $start_date = "14daysAgo";
94
        $end_date = "yesterday";
95
        $dimensions = "ga:country";
96
        $sort = "ga:pageviews";
97
        $limit  = 5;
98
    }elseif(isset($_REQUEST['ga_type']) && $_REQUEST['ga_type']=='realtime'){
99
        $metrics = "rt:activeUsers";
100
        $realtime = true;
101
    }
102
103
    # Create a new Gdata call
104
    $gaApi = new GDGoogleAnalyticsStats();
105
106
    # Check if Google sucessfully logged in
107
    if (!$gaApi->checkLogin()){
108
        echo json_encode(array('error'=>__('Please check Google Analytics Settings','geodirectory')));
109
        return false;
110
    }
111
112
    $account = $gaApi->getSingleProfile();
113
114
    if(!isset($account[0]['id'])){
115
        echo json_encode(array('error'=>__('Please check Google Analytics Settings','geodirectory')));
116
        return false;
117
    }
118
119
    $account = $account[0]['id'];
120
121
    # Set the account to the one requested
122
    $gaApi->setAccount($account);
123
124
125
126
    # Get the metrics needed to build the visits graph;
127
    try {
128
        $stats = $gaApi->getMetrics($metrics, $start_date, $end_date, $dimensions, $sort, $filters, $limit , $realtime);
0 ignored issues
show
Documentation introduced by
$dimensions is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$sort is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$filters is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Bug introduced by
It seems like $limit defined by 5 on line 97 can also be of type integer; however, GDGoogleAnalyticsStats::getMetrics() does only seem to accept boolean, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
129
    }
130
    catch (Exception $e) {
131
        print 'GA Summary Widget - there was a service error ' . $e->getCode() . ':' . $e->getMessage();
132
    }
133
134
135
    //print_r($stats);
136
    echo json_encode($stats);
137
    exit;
138
139
140
}// end GA function
141
142
143
function geodir_ga_get_token(){
144
    $at = get_option('gd_ga_access_token');
145
    $use_url = "https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=".$at;
146
    $response =  wp_remote_get($use_url,array('timeout' => 15));
147
148
    if(!empty($response['response']['code']) && $response['response']['code']==200) {//access token is valid
149
150
    return $at;
151
    }else{//else get new access token
152
153
        $refresh_at = get_option('gd_ga_refresh_token');
154
        if(!$refresh_at){
155
            echo json_encode(array('error'=>__('Not authorized, please click authorized in GD > Google analytic settings.', 'geodirectory')));exit;
156
        }
157
158
        $rat_url = "https://www.googleapis.com/oauth2/v3/token?";
159
        $client_id = "client_id=".get_option('geodir_ga_client_id');
160
        $client_secret = "&client_secret=".get_option('geodir_ga_client_secret');
161
        $refresh_token = "&refresh_token=".$refresh_at;
162
        $grant_type = "&grant_type=refresh_token";
163
164
        $rat_url_use = $rat_url.$client_id.$client_secret.$refresh_token.$grant_type;
165
166
        $rat_response =  wp_remote_post($rat_url_use,array('timeout' => 15));
167
        if(!empty($rat_response['response']['code']) && $rat_response['response']['code']==200) {
168
            $parts = json_decode($rat_response['body']);
169
170
171
            update_option('gd_ga_access_token', $parts->access_token);
172
            return $parts->access_token;
173
174
        }else{
175
            echo json_encode(array('error'=>__('Login failed', 'geodirectory')));exit;
176
        }
177
178
179
    }
180
181
}