GaController.php
6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
<?php
/**
* Created by PhpStorm.
* User: Alex Savenko
* Date: 09.02.2017
* Time: 18:12
*/
namespace App\Controllers;
use App\Model\Project;
use Google_Client;
use Google_Service_AnalyticsReporting;
use Google_Service_AnalyticsReporting_DateRange;
use Google_Service_AnalyticsReporting_Dimension;
use Google_Service_AnalyticsReporting_GetReportsRequest;
use Google_Service_AnalyticsReporting_Metric;
use Google_Service_AnalyticsReporting_ReportRequest;
use PhalconRest\Mvc\Controllers\CrudResourceController;
class GaController extends CrudResourceController {
const SECRET_JSON = 'ca4a1bd8aa14.json';
const VIEW_ID = '119240817';
const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
public function getAction() {
/** user params **/
$user_id = $this->request->get('user_id')?? '1';
$view_id= $this->request->get('view_id');
$chart = $this->request->get('chart') ?? false;
/** google params **/
$get_metrics = $this->request->get('metric') ?? 'users';
$get_dimensions = $this->request->get('dimension');
$get_start_date = $this->request->get('start') ?? '30daysAgo';
$get_end_date = $this->request->get('end') ?? 'today';
if (empty($view_id)) {
$result = [];
$projects = Project::find(['user_id' => $user_id]);
foreach ($projects as $project) {
$view_id = (string)$project->ga_view_id;
if (!empty($view_id)) {
$result[] = $this->sendGaRequest($project->name, $view_id, $get_metrics, $get_dimensions, $get_start_date, $get_end_date, $chart);
}
}
}
else {
$project = Project::findFirst(['ga_view_id' => $view_id]);
$result = $this->sendGaRequest($project->name , $view_id, $get_metrics, $get_dimensions, $get_start_date, $get_end_date, $chart);
}
return $result;
}
public function sendGaRequest($project_name, $view, $get_metrics, $get_dimensions, $start, $end, $chart = false) {
putenv('GOOGLE_APPLICATION_CREDENTIALS=/var/www/phalcon/'.self::SECRET_JSON);
$client = new Google_Client();
$client->useApplicationDefaultCredentials();
$client->setScopes([self::SCOPE]);
$analytics = new Google_Service_AnalyticsReporting($client);
/** Create the DateRange object. **/
$dateRange = new Google_Service_AnalyticsReporting_DateRange();
$dateRange->setStartDate($start);
$dateRange->setEndDate($end);
/** Create the Metrics object. **/
$metrics = [];
$get_metrics = explode(',', $get_metrics);
foreach ($get_metrics as $metric) {
$metrics_obj = new Google_Service_AnalyticsReporting_Metric();
$metrics_obj->setExpression('ga:'.$metric);
$metrics_obj->setAlias('ga:'.$metric);
$metrics[] = $metrics_obj;
}
/** Create the Dimensions object. **/
if (!empty($get_dimensions)) {
$dimensions = [];
$get_dimensions = explode(',', $get_dimensions);
foreach ($get_dimensions as $dimension) {
$dimension_obj = new Google_Service_AnalyticsReporting_Dimension();
$dimension_obj->setName("ga:".$dimension);
$dimensions[] = $dimension_obj;
}
}
//Create the ReportRequest object.
$request = new Google_Service_AnalyticsReporting_ReportRequest();
$request->setViewId($view);
$request->setDateRanges($dateRange);
$request->setIncludeEmptyRows(true);
if (!empty($dimensions)) {
$request->setDimensions(array($dimensions));
}
$request->setMetrics(array($metrics));
$body = new Google_Service_AnalyticsReporting_GetReportsRequest();
$body->setReportRequests(array($request));
$response = $analytics->reports->batchGet($body);
//have to rewrite code below (2 rows)
$response = $response->toSimpleObject();
$response = $response->reports[0]['data']['rows'];
if ($chart) {
$result = self::responseChartTransform($response, $project_name);
} else {
$result = self::responseDataTransform($response, $project_name);
}
return $result;
}
public static function responseDataTransform(array $response, $project_name) {
$result = [];
foreach ($response as $item) {
$metric_val = $item['metrics'][0]['values'];
$dimension_val = $item['dimensions'][0];
$result['name'] = $project_name;
if (count($metric_val) > 1) {
for ($i = 0; $i < count($metric_val); $i++) {
$result[$dimension_val][] = $metric_val[$i];
}
} else {
$result[$dimension_val] = $metric_val[0];
}
}
return $result;
}
public static function responseChartTransform(array $response, $project_name) {
$result = [];
foreach ($response as $item) {
$metric_val = $item['metrics'][0]['values'];
$result['name'] = $project_name;
if (count($metric_val) > 1) {
for ($i = 0; $i < count($metric_val); $i++) {
$result['data'][] = (int)$metric_val[$i];
}
} else {
$result['data'][] = (int)$metric_val[0];
}
}
return $result;
}
public function printResults($reports) {
$res = '';
for ( $reportIndex = 0; $reportIndex < count( $reports ); $reportIndex++ ) {
$report = $reports[ $reportIndex ];
$header = $report->getColumnHeader();
$dimensionHeaders = $header->getDimensions();
$metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries();
$rows = $report->getData()->getRows();
for ( $rowIndex = 0; $rowIndex < count($rows); $rowIndex++) {
$row = $rows[ $rowIndex ];
$dimensions = $row->getDimensions();
$metrics = $row->getMetrics();
for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) {
print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n");
}
for ($j = 0; $j < count( $metricHeaders ) && $j < count( $metrics ); $j++) {
$entry = $metricHeaders[$j];
$values = $metrics[$j];
//print("Metric type: " . $entry->getType() . "\n" );
for ( $valueIndex = 0; $valueIndex < count( $values->getValues() ); $valueIndex++ ) {
$value = $values->getValues()[ $valueIndex ];
$res .= "<b>" . $entry->getName() . "</b>: " . $value . '<br/>';
}
}
}
}
return $res;
}
}