Kohana_Report_GoogleAnalytics   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 244
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

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

13 Methods

Rating   Name   Duplication   Size   Complexity  
A request_params() 0 17 1
A project_id() 0 14 3
B access_token() 0 30 3
A retrieve() 0 4 1
A rows() 0 4 1
A total() 0 4 1
A max_results() 0 9 2
A dimensions() 0 9 2
A metrics() 0 9 2
A sort() 0 9 2
A filters() 0 9 2
A segment() 0 9 2
A start_index() 0 9 2
1
<?php
2
3
use OAuth\OAuth2\Service\Google;
4
use OAuth\Common\Storage\Session;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Session.

Let’s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let’s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use OAuth\Common\Consumer\Credentials;
6
7
/**
8
 * An interface for google analytics API
9
 *
10
 * @package    Despark/services-manager
11
 * @author     Ivan Kerin
12
 * @copyright  (c) 2012 Despark Ltd.
13
 * @license    http://creativecommons.org/licenses/by-sa/3.0/legalcode
14
 */
15
class Kohana_Report_GoogleAnalytics extends Report
16
{
17
	const URL = 'https://www.googleapis.com/analytics/v3/data/ga';
18
19
	protected $_metrics;
20
	protected $_sort;
21
	protected $_max_results;
22
	protected $_dimensions;
23
	protected $_project_id;
24
	protected $_access_token;
25
	protected $_filters;
26
	protected $_segment;
27
	protected $_start_index;
28
	protected $_date_template = 'Y-m-d';
29
30
	/**
31
	 * Build all the request query parameters needed to access the google analytics API
32
	 * @return array
33
	 */
34
	public function request_params()
35
	{
36
		$data = array(
37
			'ids' => $this->project_id(),
38
			'access_token' => $this->access_token(),
39
			'start-date' =>  $this->start_date(),
40
			'end-date' => $this->end_date(),
41
			'metrics' => $this->metrics(),
42
			'dimensions' => $this->dimensions(),
43
			'max-results' => $this->max_results(),
44
			'sort' => $this->sort(),
45
			'filters' => $this->filters(),
46
			'segment' => $this->segment(),
47
			'start-index' => $this->start_index(),
48
		);
49
		return array_filter($data);
50
	}
51
52
	/**
53
	 * Return the project_id set in the config or set it for this report
54
	 * @return string|$this
55
	 */
56
	public function project_id($project_id = NULL)
57
	{
58
		if ($project_id !== NULL)
59
		{
60
			$this->_project_id = $project_id;
61
			return $this;
62
		}
63
64
		if ( ! $this->_project_id)
65
		{
66
			$this->_project_id = Kohana::$config->load('services-manager.reports.googleanalytics.project_id');
67
		}
68
		return $this->_project_id;
69
	}
70
71
	/**
72
	 * Generate a new access token for google analytics API using client_id, client_secret and refresh_token, set in the config
73
	 * @return string
74
	 */
75
	public function access_token()
76
	{
77
		if ( ! $this->_access_token)
78
		{
79
			$config = Kohana::$config->load('services-manager.reports.googleanalytics');
80
81
			if (count($missing_keys = array_diff(array('refresh_token', 'client_id', 'client_secret'), array_keys($config))))
82
				throw new Kohana_Exception('Must set :keys for googleanalytics service configuration', array(':keys' => join(', ', $missing_keys)));
83
84
			// require_once Kohana::find_file("vendor", "googleoauth");
85
86
			// Session storage
87
			$storage = new Session();
88
			// Setup the credentials for the requests
89
			$credentials = new Credentials(
90
				$config['client_id'],
91
				$config['client_secret'],
92
				Request::current()->url()
93
			);
94
95
			$serviceFactory = new \OAuth\ServiceFactory();
96
			// Instantiate the Google service using the credentials, http client and storage mechanism for the token
97
			$googleService = $serviceFactory->createService('google', $credentials, $storage, array('userinfo_email', 'userinfo_profile'));
98
			$tokenInterface = new \OAuth\OAuth2\Token\StdOAuth2Token(NULL, $config['refresh_token']);
99
			$token = $googleService->refreshAccessToken($tokenInterface);
100
			$this->_access_token = $token->getAccessToken();
101
		}
102
103
		return $this->_access_token;
104
	}
105
106
	/**
107
	 * Get the result from calling Google Anlaytics API
108
	 * @return array
109
	 */
110
	public function retrieve()
111
	{
112
		return json_decode(Request::factory(Report_GoogleAnalytics::URL)->query($this->request_params())->execute()->body(), TRUE);
113
	}
114
115
	/**
116
	 * Rows from Google Analytics API response
117
	 * @return array
118
	 */
119
	public function rows()
120
	{
121
		return (array) Arr::get($this->retrieve(), 'rows');
122
	}
123
124
	/**
125
	 * Get 'totals' from Google Analytics API response
126
	 * @return mixed
127
	 */
128
	public function total()
129
	{
130
		return Arr::path($this->retrieve(), 'totalsForAllResults.'.$this->metrics());
131
	}
132
133
	/**
134
	 * Getter / Setter
135
	 * The maximum number of rows to include in the response.
136
	 *
137
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#maxResults
138
	 * @param  int $max_results
139
	 * @return int|$this
140
	 */
141
	public function max_results($max_results = NULL)
142
	{
143
		if ($max_results !== NULL)
144
		{
145
			$this->_max_results = $max_results;
146
			return $this;
147
		}
148
		return $this->_max_results;
149
	}
150
151
	/**
152
	 * Getter / Setter
153
	 * A list of comma-separated dimensions for your Analytics data, such as ga:browser,ga:city.
154
	 *
155
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#dimensions
156
	 * @param  string $dimensions
157
	 * @return string|$this
158
	 */
159
	public function dimensions($dimensions = NULL)
160
	{
161
		if ($dimensions !== NULL)
162
		{
163
			$this->_dimensions = $dimensions;
164
			return $this;
165
		}
166
		return $this->_dimensions;
167
	}
168
169
	/**
170
	 * Getter / Setter
171
	 * A list of comma-separated metrics, such as ga:visits,ga:bounces.
172
	 *
173
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#metrics
174
	 * @param  string $metrics
175
	 * @return string|$this
176
	 */
177
	public function metrics($metrics = NULL)
178
	{
179
		if ($metrics !== NULL)
180
		{
181
			$this->_metrics = $metrics;
182
			return $this;
183
		}
184
		return $this->_metrics;
185
	}
186
187
	/**
188
	 * Getter / Setter
189
	 * A list of comma-separated dimensions and metrics indicating the sorting order and sorting direction for the returned data.
190
	 *
191
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#sort
192
	 * @param  string $sort
193
	 * @return string|$this
194
	 */
195
	public function sort($sort = NULL)
196
	{
197
		if ($sort !== NULL)
198
		{
199
			$this->_sort = $sort;
200
			return $this;
201
		}
202
		return $this->_sort;
203
	}
204
205
	/**
206
	 * Getter / Setter
207
	 * Dimension or metric filters that restrict the data returned for your request.
208
	 *
209
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#filters
210
	 * @param  string $filters
211
	 * @return string|$this
212
	 */
213
	public function filters($filters = NULL)
214
	{
215
		if ($filters !== NULL)
216
		{
217
			$this->_filters = $filters;
218
			return $this;
219
		}
220
		return $this->_filters;
221
	}
222
223
	/**
224
	 * Getter / Setter
225
	 * Segments the data returned for your request.
226
	 *
227
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#segment
228
	 * @param  string $segment
229
	 * @return string|$this
230
	 */
231
	public function segment($segment = NULL)
232
	{
233
		if ($segment !== NULL)
234
		{
235
			$this->_segment = $segment;
236
			return $this;
237
		}
238
		return $this->_segment;
239
	}
240
241
	/**
242
	 * Getter / Setter
243
	 * The first row of data to retrieve, starting at 1. Use this parameter as a pagination mechanism along with the max-results parameter.
244
	 *
245
	 * @link https://developers.google.com/analytics/devguides/reporting/core/v3/reference#startIndex
246
	 * @param  string $start_index
247
	 * @return string|$this
248
	 */
249
	public function start_index($start_index = NULL)
250
	{
251
		if ($start_index !== NULL)
252
		{
253
			$this->_start_index = $start_index;
254
			return $this;
255
		}
256
		return $this->_start_index;
257
	}
258
}
259
260