Blame view

app/library/App/Controllers/GaController.php 19.7 KB
b38ef228   Alex Savenko   generate GaResource
1
2
3
4
5
6
7
8
9
10
11
  <?php
  /**
   * Created by PhpStorm.
   * User: Alex Savenko
   * Date: 09.02.2017
   * Time: 18:12
   */
  
  namespace App\Controllers;
  
  
33813a62   Alex Savenko   функция проверки ...
12
  use PhalconRest\Mvc\Controllers\CrudResourceController;
a941da22   Alex Savenko   ga output
13
  use App\Model\Project;
5de5ebae   Alex Savenko   фиксы по гуглу: м...
14
  use DateTime;
897d06c3   Alex Savenko   generate GaResource
15
16
17
  use Google_Client;
  use Google_Service_AnalyticsReporting;
  use Google_Service_AnalyticsReporting_DateRange;
f51dd710   Alex Savenko   dimensions +dynam...
18
  use Google_Service_AnalyticsReporting_Dimension;
897d06c3   Alex Savenko   generate GaResource
19
20
  use Google_Service_AnalyticsReporting_GetReportsRequest;
  use Google_Service_AnalyticsReporting_Metric;
5de5ebae   Alex Savenko   фиксы по гуглу: м...
21
  use Google_Service_AnalyticsReporting_OrderBy;
897d06c3   Alex Savenko   generate GaResource
22
  use Google_Service_AnalyticsReporting_ReportRequest;
33813a62   Alex Savenko   функция проверки ...
23
24
25
  use Codeception\Exception\ContentNotFound;
  use PhalconApi\Exception;
  use PhalconApi\Constants\ErrorCodes;
b38ef228   Alex Savenko   generate GaResource
26
27
28
  
  class GaController extends CrudResourceController {
  
897d06c3   Alex Savenko   generate GaResource
29
30
      const SECRET_JSON = 'ca4a1bd8aa14.json';
      const VIEW_ID = '119240817';
c9087298   Alex Savenko   ga output
31
      const SCOPE = 'https://www.googleapis.com/auth/analytics.readonly';
b38ef228   Alex Savenko   generate GaResource
32
  
24fc8bd1   Alex Savenko   add php docs for ...
33
34
35
36
37
38
      /**
       * Check permission for input project
       *
       * @return array
       * @throws Exception
       */
33813a62   Alex Savenko   функция проверки ...
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
      public function checkAction() {
  
          $data = $this->getPostedData();
  
          /** user params **/
          $view_id = $data['view_id'];
  
          if (empty($view_id)) {
              $msg = 'Post-data is invalid, empty `view_id` value';
              throw new Exception(ErrorCodes::DATA_NOT_FOUND, $msg, ['view_id' => $view_id]);
          }
  
          $result['view_id'] = $view_id;
  
          try {
              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);
  
              $request = new Google_Service_AnalyticsReporting_ReportRequest();
              $request->setViewId($view_id);
  
              $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
              $body->setReportRequests(array($request));
  
              $analytics->reports->batchGet($body);
          }
          catch (\Exception $e) {
              if ($e->getCode() == 403) {
                  $result['status'] = 'error';
                  return $result;
              }
              else {
                  return $e->getMessage();
              }
          }
  
          $result['status'] = 'success';
  
          return $result;
  
      }
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
84
85
86
87
88
      /**
       * Main action for /ga request. Send it google report api.
       *
       * @return array
       */
897d06c3   Alex Savenko   generate GaResource
89
90
      public function getAction() {
  
c9087298   Alex Savenko   ga output
91
          /** user params **/
0c1a07f0   Alex Savenko   add filter param ...
92
93
94
          $user_id    = $this->request->get('user_id')?? '1';
          $view_id    = $this->request->get('view_id');
          $chart      = $this->request->get('chart') ?? false;
c9087298   Alex Savenko   ga output
95
96
  
          /** google params **/
0c1a07f0   Alex Savenko   add filter param ...
97
98
99
100
101
          $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';
          $filter_expression  = $this->request->get('filter');
5de5ebae   Alex Savenko   фиксы по гуглу: м...
102
103
104
105
106
107
108
109
110
111
112
113
114
115
          $sort               = $this->request->get('sort');
          $sort_type          = $this->request->get('sort_type');
          $max_result         = $this->request->get('max_result');
  
  
          /** if empty $_GET["view_id"] send request to all projects in user's model  **/
              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,
86777356   Alex Savenko   кастомные фильды ...
116
                              $project->id,
5de5ebae   Alex Savenko   фиксы по гуглу: м...
117
118
119
120
121
122
123
124
125
126
127
128
                              $view_id,
                              $get_metrics,
                              $get_dimensions,
                              $get_start_date,
                              $get_end_date,
                              $chart,
                              $filter_expression,
                              $sort,
                              $sort_type,
                              $max_result
                          );
                      }
1d97c107   Alex Savenko   ga output
129
                  }
9ba864b0   Alex Savenko   ga output
130
              }
5de5ebae   Alex Savenko   фиксы по гуглу: м...
131
132
133
134
135
136
              else {
                  $project = Project::findFirst([
                      "ga_view_id = '$view_id'",
                  ]);
                  $result = $this->sendGaRequest(
                      $project->name,
86777356   Alex Savenko   кастомные фильды ...
137
                      $project->id,
5de5ebae   Alex Savenko   фиксы по гуглу: м...
138
139
140
141
142
143
144
145
146
147
148
149
150
                      $view_id,
                      $get_metrics,
                      $get_dimensions,
                      $get_start_date,
                      $get_end_date,
                      $chart,
                      $filter_expression,
                      $sort,
                      $sort_type,
                      $max_result
                  );
              }
          /** --------------------------------------------------------------- **/
2a57dd72   Alex Savenko   ga fix
151
          return $result;
129bec7c   Alex Savenko   ga output
152
153
154
  
      }
  
c6c9c77e   Alex Savenko   add php docs to g...
155
156
157
158
      /**
       * Send request to Google Analytics Reporting API
       *
       * @param   string  $project_name
86777356   Alex Savenko   кастомные фильды ...
159
       * @param   int     $project_id
c6c9c77e   Alex Savenko   add php docs to g...
160
161
162
163
164
165
166
       * @param   string  $view
       * @param   string  $get_metrics
       * @param   string  $get_dimensions
       * @param   string  $start
       * @param   string  $end
       * @param   bool    $chart
       * @param   string  $filter_expression
5de5ebae   Alex Savenko   фиксы по гуглу: м...
167
168
169
       * @param   string  $sort
       * @param   string  $sort_type
       * @param   int     $max_result
c6c9c77e   Alex Savenko   add php docs to g...
170
171
       * @return  array
       */
86777356   Alex Savenko   кастомные фильды ...
172
      public function sendGaRequest($project_name, $project_id, $view, $get_metrics, $get_dimensions, $start, $end, $chart = false, $filter_expression = null, $sort = null, $sort_type = 'desc', $max_result = 50000) {
129bec7c   Alex Savenko   ga output
173
  
897d06c3   Alex Savenko   generate GaResource
174
175
176
          putenv('GOOGLE_APPLICATION_CREDENTIALS=/var/www/phalcon/'.self::SECRET_JSON);
          $client = new Google_Client();
          $client->useApplicationDefaultCredentials();
c9087298   Alex Savenko   ga output
177
          $client->setScopes([self::SCOPE]);
897d06c3   Alex Savenko   generate GaResource
178
179
          $analytics = new Google_Service_AnalyticsReporting($client);
  
c9087298   Alex Savenko   ga output
180
          /** Create the DateRange object. **/
5de5ebae   Alex Savenko   фиксы по гуглу: м...
181
182
183
184
              $dateRange = new Google_Service_AnalyticsReporting_DateRange();
              $dateRange->setStartDate($start);
              $dateRange->setEndDate($end);
          /** ---------------------------- **/
29f4a05f   Alex Savenko   multiple metrics
185
  
c9087298   Alex Savenko   ga output
186
          /** Create the Metrics object. **/
5de5ebae   Alex Savenko   фиксы по гуглу: м...
187
188
189
190
191
192
193
194
195
              $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;
              }
          /** -------------------------- **/
897d06c3   Alex Savenko   generate GaResource
196
  
c9087298   Alex Savenko   ga output
197
          /** Create the Dimensions object.  **/
5de5ebae   Alex Savenko   фиксы по гуглу: м...
198
199
200
201
202
203
204
205
              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;
                  }
b22a7c02   Alex Savenko   empty dimension
206
              }
5de5ebae   Alex Savenko   фиксы по гуглу: м...
207
          /** ----------------------------- **/
f51dd710   Alex Savenko   dimensions +dynam...
208
  
c6c9c77e   Alex Savenko   add php docs to g...
209
          /** Create the ReportRequest object.  **/
5de5ebae   Alex Savenko   фиксы по гуглу: м...
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
              $request = new Google_Service_AnalyticsReporting_ReportRequest();
              $request->setViewId($view);
              $request->setPageSize($max_result);
              $request->setDateRanges($dateRange);
              $request->setIncludeEmptyRows(true);
              /** Create the Ordering **/
                  if (isset($sort)) {
                      $ordering = new Google_Service_AnalyticsReporting_OrderBy();
                      $ordering->setFieldName("ga:".$sort);
                      $ordering->setOrderType("VALUE");
                      $ordering->setSortOrder("DESCENDING");
                          if ($sort_type == 'asc') {
                              $ordering->setSortOrder("ASCENDING");
                          }
                      $request->setOrderBys($ordering);
                  }
              /** --------------- **/
              if (!empty($dimensions)) {
                  $request->setDimensions(array($dimensions));
              }
              $request->setMetrics(array($metrics));
              if (!empty($filter_expression)) {
                  $request->setFiltersExpression("ga:".$filter_expression);
              }
              /** compute days in request **/
                  $request_date['start']   =  new DateTime(date('d.m.Y', strtotime($request->getDateRanges()['startDate'])));
                  $request_date['end']     =  new DateTime(date('d.m.Y', strtotime($request->getDateRanges()['endDate'])));
                  $request_days = (date_diff($request_date['start'], $request_date['end'])->days)+1;
              /** ----------------------- **/
              $request_dim = $request->getDimensions();
              if (count($request_dim[0]) == 2) {
                  $request_dim = $request_dim[0][1]->name;
              }
              else {
                  $request_dim = $request_dim[0][0]->name;
              }
              $iterations = self::countIterations($request_dim, $request_days);
          /** ---------------------------- **/
897d06c3   Alex Savenko   generate GaResource
248
  
29f4a05f   Alex Savenko   multiple metrics
249
          $body = new Google_Service_AnalyticsReporting_GetReportsRequest();
c6d3dfe5   Alex Savenko   registration
250
          $body->setReportRequests(array($request));
897d06c3   Alex Savenko   generate GaResource
251
  
c6d3dfe5   Alex Savenko   registration
252
          $response =  $analytics->reports->batchGet($body);
897d06c3   Alex Savenko   generate GaResource
253
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
254
          //can be refactored (code below, 2 rows)
a6a1fb9f   Alex Savenko   ga output
255
          $response = $response->toSimpleObject();
a6a1fb9f   Alex Savenko   ga output
256
          $response = $response->reports[0]['data']['rows'];
9b8fbac2   Alex Savenko   ga output
257
  
86777356   Alex Savenko   кастомные фильды ...
258
          $custom_fields = ['name' => $project_name, 'view_id' => (int)$view, 'id' => $project_id];
7e1d4fa3   Alex Savenko   ga output
259
          if ($chart) {
86777356   Alex Savenko   кастомные фильды ...
260
              $result = self::responseDataTransform($response, $iterations, $request_dim, $custom_fields);
5de5ebae   Alex Savenko   фиксы по гуглу: м...
261
              $result = self::chartTransform($result);
7e1d4fa3   Alex Savenko   ga output
262
          } else {
86777356   Alex Savenko   кастомные фильды ...
263
              $result = self::responseDataTransform($response, $iterations, $request_dim, $custom_fields);
7e1d4fa3   Alex Savenko   ga output
264
          }
5937dcc7   Alex Savenko   ga output
265
  
5285e167   Alex Savenko   ga output
266
          return $result;
5937dcc7   Alex Savenko   ga output
267
268
269
  
      }
  
c6c9c77e   Alex Savenko   add php docs to g...
270
271
272
273
      /**
       * Data-transformer for tables. Used by default.
       *
       * @param   array   $response
5de5ebae   Alex Savenko   фиксы по гуглу: м...
274
275
       * @param   int     $iterations
       * @param   string  $request_dimension
86777356   Alex Savenko   кастомные фильды ...
276
       * @param   array   $custom_fields
c6c9c77e   Alex Savenko   add php docs to g...
277
278
       * @return  array
       */
86777356   Alex Savenko   кастомные фильды ...
279
      public static function responseDataTransform(array $response, $iterations, $request_dimension, $custom_fields) {
5937dcc7   Alex Savenko   ga output
280
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
281
282
283
          $result     = [];
          $int_query  = true;
          $max_values = 0;
9cbda58b   Alex Savenko   ga output
284
  
c04bfb94   Alex Savenko   ga output
285
          foreach ($response as $item) {
d29dde0e   Alex Savenko   ga output
286
287
288
  
              $metric_val = $item['metrics'][0]['values'];
              $dimension_val = $item['dimensions'][0];
5de5ebae   Alex Savenko   фиксы по гуглу: м...
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
              $dimension_count = count($item['dimensions']);
  
              /** remove "0001" from dimension keys **/
                  for ($i = 0; $i < $dimension_count; $i++) {
                      $current_value = $item['dimensions'][$i];
                      if (ctype_digit(strval($current_value))) {
                          $item['dimensions'][$i] = (int)$current_value;
                          if ($i == 0) {
                              $dimension_val = (int)$current_value;
                          }
                      }
                      elseif ($i == 1) {
                          $int_query = false;
                      }
                  }
              /** --------------------------------- **/
d29dde0e   Alex Savenko   ga output
305
  
889ea43e   Alex Savenko   ga output
306
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
              if ($dimension_count == 2) {
                  $dimension_val_2 = $item['dimensions'][1];
                  if (count($metric_val) > 1) {
                      for ($i = 0; $i < count($metric_val); $i++) {
                          $result[$dimension_val][$dimension_val_2][] = (int)$metric_val[$i];
                      }
                  } else {
                      $result[$dimension_val][$dimension_val_2] = (int)$metric_val[0];
                  }
              }
              else {
                  if (count($metric_val) > 1) {
                      for ($i = 0; $i < count($metric_val); $i++) {
                          $result[$dimension_val][] = (int)$metric_val[$i];
                      }
                  } else {
                      $result[$dimension_val] = (int)$metric_val[0];
d29dde0e   Alex Savenko   ga output
324
                  }
d29dde0e   Alex Savenko   ga output
325
              }
5de5ebae   Alex Savenko   фиксы по гуглу: м...
326
327
328
329
330
  
              $dim_val_count = count($result[$dimension_val]);
              if ($dim_val_count > $max_values) $max_values = $dim_val_count;
              unset($dim_val_count);
  
9cbda58b   Alex Savenko   ga output
331
332
          }
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
          $int_query = self::checkDimension($request_dimension);
  
          /** ------ filling missing data ------ **/
              if ($int_query) {
                  foreach ($result as $key => $item) {
                      if (!is_array($item)) break;
                      $iterations = $iterations ?? $max_values;
                      for ($i = 0; $i < $iterations; $i++) {
                          $result[$key][$i] = $item[$i] ?? 0;
                      }
                      ksort($result[$key]);
                  }
              }
          /** --------------------------------- **/
  
          /** ----- add custom fields ------ **/
86777356   Alex Savenko   кастомные фильды ...
349
350
351
              foreach ($custom_fields as $key => $value) {
                  $result[$key] = $value ?? 'Неизвестный';
              }
5de5ebae   Alex Savenko   фиксы по гуглу: м...
352
353
          /** ------------------------------ **/
  
5937dcc7   Alex Savenko   ga output
354
          return $result;
05915c96   Alex Savenko   ga output
355
  
7fe1d3b2   Alex Savenko   create response
356
      }
5937dcc7   Alex Savenko   ga output
357
  
c6c9c77e   Alex Savenko   add php docs to g...
358
359
360
      /**
       * Data-transformer for charts, when query string contains "?chart=true"
       *
5de5ebae   Alex Savenko   фиксы по гуглу: м...
361
362
363
364
       * @param   array   $data
       * @return  array
       */
      public static function chartTransform(array $data) {
86777356   Alex Savenko   кастомные фильды ...
365
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
366
          $result = [];
86777356   Alex Savenko   кастомные фильды ...
367
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
368
          foreach ($data as $key => $value) {
86777356   Alex Savenko   кастомные фильды ...
369
370
371
372
  
              /** Skip custom field **/
                  if ($key === 'name' || $key == 'id' || $key == 'view_id') {
                      $result[$key] = $value;
5de5ebae   Alex Savenko   фиксы по гуглу: м...
373
                  }
86777356   Alex Savenko   кастомные фильды ...
374
375
376
              /** ---------------- **/
  
              /** Remove keys and add 'data' array **/
5de5ebae   Alex Savenko   фиксы по гуглу: м...
377
                  else {
86777356   Alex Savenko   кастомные фильды ...
378
379
380
381
382
383
384
385
                      if (!is_array($value)) {
                          $result['data'][] = $value;
                      }
                      else {
                          foreach ($value as $v_key => $v_value) {
                              $result['data'][$key][$v_key] = $v_value;
                          }
                          ksort($result['data'][$key]);
5de5ebae   Alex Savenko   фиксы по гуглу: м...
386
                      }
5de5ebae   Alex Savenko   фиксы по гуглу: м...
387
                  }
86777356   Alex Savenko   кастомные фильды ...
388
389
              /** ------------------------------- **/
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
          }
  
          return $result;
      }
  
      /**
       * Deprecated
       *
       * @param array $data
       * @return array
       */
      public static function chartTransform1(array $data) {
  
          $result = [];
          $max    = 0;
  
          foreach ($data as $key => $value) {
              if ($key == 'name') {
                  $result[$key] = $value;
                  continue;
              }
  
              if (!is_array($value)) break;
  
              /** ------ check array keys for int values --- **/
                  $count = count($value);
                  if ($count > $max) $max = $count;
                  $int_type = true;
                  foreach ($value as $inc_key => $inc_value) {
                      if (!preg_match('/\d+/', $inc_key)) {
                          $int_type = false;
                          break;
                      }
                  }
              /** ------------------------------------------ **/
  
              /** rewrites keys like "0001" to integer type  **/
                  if ($int_type) {
                      $bad_keys = array_keys($value);
                      for ($i = 0; $i < $count; $i++) {
                          $good_key = (int)$bad_keys[$i];
                          $result[$key][$good_key] = $value[$bad_keys[$i]] ?? 0;
                      }
                  }
              /** ------------------------------------------ **/
  
          }
  
          /** ---------- filling missing data ---------- **/
              foreach ($result as $key => $value) {
                  if ($key == 'name') continue;
                  for ($i = 0; $i < $max; $i++) {
                      $result[$key][$i] = (int)$result[$key][$i] ?? 0;
                  }
                  ksort($result[$key]);
              }
          /** ------------------------------------------ **/
  
          return $result;
  
      }
  
      /**
       * Deprecated
       *
c6c9c77e   Alex Savenko   add php docs to g...
455
456
457
458
       * @param   array   $response
       * @param   string  $project_name
       * @return  array
       */
7e1d4fa3   Alex Savenko   ga output
459
460
461
      public static function responseChartTransform(array $response, $project_name) {
  
          $result = [];
a7c416d0   Alex Savenko   ga output
462
  
7e1d4fa3   Alex Savenko   ga output
463
464
          foreach ($response as $item) {
  
92a5b7e0   Alex Savenko   ga fix
465
              $result['name'] = $project_name;
7e1d4fa3   Alex Savenko   ga output
466
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
              $metric_val = $item['metrics'][0]['values'];
              $dimension_val = $item['dimensions'][0];
              $dimension_count = count($item['dimensions']);
  
              if ($dimension_count == 2) {
                  $dimension_val_2 = $item['dimensions'][1];
                  if (count($metric_val) > 1) {
                      for ($i = 0; $i < count($metric_val); $i++) {
                          $result['data'][$dimension_val][] = (int)$metric_val[$i];
                      }
                  } else {
                      $result['data'][$dimension_val][] = (int)$metric_val[0];
                  }
              }
              else {
                  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];
7e1d4fa3   Alex Savenko   ga output
488
                  }
7e1d4fa3   Alex Savenko   ga output
489
490
491
492
493
494
495
              }
          }
  
          return $result;
  
      }
  
5de5ebae   Alex Savenko   фиксы по гуглу: м...
496
497
498
499
500
501
502
503
504
505
      /**
       * Compute count of fields
       *
       * @param   string  $request_dim
       * @param   int     $request_days
       * @return  int
       * @throws  ContentNotFound if functions params is empty
       */
      public static function countIterations($request_dim, $request_days) {
  
33813a62   Alex Savenko   функция проверки ...
506
507
          if (empty($request_dim))  throw new ContentNotFound('PHP: request_dim not found', ErrorCodes::DATA_NOT_FOUND);
          if (empty($request_days)) throw new ContentNotFound('PHP: request_days not found', ErrorCodes::DATA_NOT_FOUND);
5de5ebae   Alex Savenko   фиксы по гуглу: м...
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
          switch ($request_dim) {
              case 'ga:nthDay':
                  $iterations = $request_days*1;
                  break;
              case 'ga:nthHour':
                  $iterations = $request_days*24;
                  break;
              case 'ga:nthMinute':
                  $iterations = $request_days*24*60;
                  break;
              default:
                  $iterations = null;
          }
  
          return $iterations;
  
      }
  
      /**
       * Boolean indicator for chart transformer
       *
       * @param   string $dimension
       * @return  bool
       */
      public static function checkDimension($dimension) {
  
          $nthArray = ['ga:nthMonth', 'ga:nthWeek', 'ga:nthDay', 'ga:nthMinute', 'ga:nthHour'];
  
          return in_array($dimension, $nthArray) ? true : false;
  
      }
5937dcc7   Alex Savenko   ga output
539
  
c6c9c77e   Alex Savenko   add php docs to g...
540
541
542
      /**
       * without usage, from google docs.
       */
5937dcc7   Alex Savenko   ga output
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
      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;
      }
  
b38ef228   Alex Savenko   generate GaResource
575
  }