Analytics::populateAccountExplorerSettings()   A
last analyzed

Complexity

Conditions 6
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 14
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 24
rs 9.2222
1
<?php
2
/**
3
 * @link      https://dukt.net/analytics/
4
 * @copyright Copyright (c) 2022, Dukt
5
 * @license   https://github.com/dukt/analytics/blob/master/LICENSE.md
6
 */
7
8
namespace dukt\analytics\apis;
9
10
use Craft;
11
use dukt\analytics\base\Api;
12
use dukt\analytics\Plugin;
13
use \Google_Service_Analytics;
14
use \Google_Service_Analytics_Columns;
15
16
class Analytics extends Api
17
{
18
    // Public Methods
19
    // =========================================================================
20
21
    /**
22
     * @return Google_Service_Analytics
23
     * @throws \yii\base\InvalidConfigException
24
     */
25
    public function getService()
26
    {
27
        $client = $this->getClient();
28
29
        return new Google_Service_Analytics($client);
30
    }
31
32
    /**
33
     * Get columns.
34
     *
35
     * @return Google_Service_Analytics_Columns
36
     * @throws \yii\base\InvalidConfigException
37
     */
38
    public function getColumns()
39
    {
40
        return Plugin::$plugin->getApis()->getAnalytics()->getService()->metadata_columns->listMetadataColumns('ga');
41
    }
42
43
    /**
44
     * Get account explorer data.
45
     *
46
     * @return array
47
     * @throws \yii\base\InvalidConfigException
48
     */
49
    public function getAccountExplorerData(): array
50
    {
51
        return [
52
            'accounts' => $this->getAllAccounts(),
53
            'properties' => $this->getAllProperties(),
54
            'views' => $this->getAllViews(),
55
        ];
56
    }
57
58
    /**
59
     * Populate Account Explorer Settings
60
     *
61
     * @param array $settings
62
     *
63
     * @return array
64
     * @throws \yii\base\InvalidConfigException
65
     */
66
    public function populateAccountExplorerSettings($settings = [])
67
    {
68
        if (!empty($settings['accountId']) && !empty($settings['webPropertyId']) && !empty($settings['profileId'])) {
69
            $apiAccounts = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_accounts->listManagementAccounts();
70
71
            $account = null;
72
73
            foreach ($apiAccounts as $apiAccount) {
74
                if ($apiAccount->id == $settings['accountId']) {
75
                    $account = $apiAccount;
76
                }
77
            }
78
79
            $webProperty = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_webproperties->get($settings['accountId'], $settings['webPropertyId']);
80
            $profile = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_profiles->get($settings['accountId'], $settings['webPropertyId'], $settings['profileId']);
81
82
            $settings['accountName'] = $account->name;
83
            $settings['webPropertyName'] = $webProperty->name;
84
            $settings['internalWebPropertyId'] = $webProperty->internalWebPropertyId;
85
            $settings['profileCurrency'] = $profile->currency;
86
            $settings['profileName'] = $profile->name;
87
        }
88
89
        return $settings;
90
    }
91
92
    /**
93
     * Parse Report Response
94
     *
95
     * @param $data
96
     *
97
     * @return array
98
     */
99
    public function parseReportResponse($data): array
100
    {
101
        $cols = $this->parseReportResponseCols($data);
102
        $rows = $this->parseReportResponseRows($data, $cols);
103
104
        return [
105
            'cols' => $cols,
106
            'rows' => $rows
107
        ];
108
    }
109
110
    // Private Methods
111
    // =========================================================================
112
113
    /**
114
     * @return array
115
     * @throws \yii\base\InvalidConfigException
116
     */
117
    private function getAllAccounts(): array
118
    {
119
        $startIndex = 1;
120
        $maxResults = 1000;
121
        $managementAccounts = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_accounts;
122
123
        $response = $managementAccounts->listManagementAccounts([
124
            'start-index' => $startIndex,
125
            'max-results' => $maxResults,
126
        ]);
127
128
        $totalResults = (int) $response->totalResults;
129
130
        if ($totalResults === 0) {
131
            return [];
132
        }
133
134
        $items = [];
135
        $index = 0;
136
137
        $items[] = $response->toSimpleObject()->items;
138
        $index += count($response->toSimpleObject()->items);
139
140
        while($index < $totalResults) {
141
            $startIndex = $index + 1;
142
143
            $response = $managementAccounts->listManagementAccounts([
144
                'start-index' => $startIndex,
145
                'max-results' => $maxResults,
146
            ]);
147
148
            $items[] = $response->toSimpleObject()->items;
149
            $index += count($response->toSimpleObject()->items);
150
        }
151
152
        return array_merge(...$items);
153
    }
154
155
    /**
156
     * @return array
157
     * @throws \yii\base\InvalidConfigException
158
     */
159
    private function getAllProperties(): array
160
    {
161
        $startIndex = 1;
162
        $maxResults = 1000;
163
        $managementWebProperties = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_webproperties;
164
165
        $response = $managementWebProperties->listManagementWebproperties('~all', [
166
            'start-index' => $startIndex,
167
            'max-results' => $maxResults,
168
        ]);
169
170
        $totalResults = (int) $response->totalResults;
171
172
        if ($totalResults === 0) {
173
            return [];
174
        }
175
176
        $items = [];
177
        $index = 0;
178
179
        $items[] = $response->toSimpleObject()->items;
180
        $index += count($response->toSimpleObject()->items);
181
182
        while($index < $totalResults) {
183
            $startIndex = $index + 1;
184
185
            $response = $managementWebProperties->listManagementWebproperties('~all', [
186
                'start-index' => $startIndex,
187
                'max-results' => $maxResults,
188
            ]);
189
190
            $items[] = $response->toSimpleObject()->items;
191
            $index += count($response->toSimpleObject()->items);
192
        }
193
194
        return array_merge(...$items);
195
    }
196
197
    /**
198
     * @return array
199
     * @throws \yii\base\InvalidConfigException
200
     */
201
    private function getAllViews(): array
202
    {
203
        $startIndex = 1;
204
        $maxResults = 1000;
205
        $managementWebProfiles = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_profiles;
206
207
        $response = $managementWebProfiles->listManagementProfiles('~all', '~all', [
208
            'start-index' => $startIndex,
209
            'max-results' => $maxResults,
210
        ]);
211
212
        $totalResults = (int) $response->totalResults;
213
214
        if ($totalResults === 0) {
215
            return [];
216
        }
217
218
        $items = [];
219
        $index = 0;
220
221
        $items[] = $response->toSimpleObject()->items;
222
        $index += count($response->toSimpleObject()->items);
223
224
        while($index < $totalResults) {
225
            $startIndex = $index + 1;
226
227
            $response = $managementWebProfiles->listManagementProfiles('~all', '~all', [
228
                'start-index' => $startIndex,
229
                'max-results' => $maxResults,
230
            ]);
231
232
            $items[] = $response->toSimpleObject()->items;
233
            $index += count($response->toSimpleObject()->items);
234
        }
235
236
        return array_merge(...$items);
237
    }
238
239
    /**
240
     * @param array $data
241
     * @return array
242
     */
243
    private function parseReportResponseCols(array $data): array
244
    {
245
        $cols = [];
246
247
        foreach ($data['columnHeaders'] as $col) {
248
            $dataType = $col->dataType;
249
            $id = $col->name;
250
            $label = Plugin::$plugin->metadata->getDimMet($col->name);
251
            $type = strtolower($dataType);
252
253
            switch ($col->name) {
254
                case 'ga:date':
255
                case 'ga:yearMonth':
256
                    $type = 'date';
257
                    break;
258
259
                case 'ga:continent':
260
                    $type = 'continent';
261
                    break;
262
                case 'ga:subContinent':
263
                    $type = 'subContinent';
264
                    break;
265
266
                case 'ga:latitude':
267
                case 'ga:longitude':
268
                    $type = 'float';
269
                    break;
270
            }
271
272
            $cols[] = [
273
                'type' => $type,
274
                'dataType' => $dataType,
275
                'id' => $id,
276
                'label' => Craft::t('analytics', $label),
277
            ];
278
        }
279
280
        return $cols;
281
    }
282
283
    /**
284
     * @param array $data
285
     * @param array $cols
286
     * @return array
287
     */
288
    private function parseReportResponseRows(array $data, array $cols): array
289
    {
290
        $rows = [];
291
292
        if ($data['rows']) {
293
            $rows = $data->rows;
294
295
            foreach ($rows as $kRow => $row) {
296
                foreach ($row as $_valueKey => $_value) {
297
                    $col = $cols[$_valueKey];
298
299
                    $value = $this->formatRawValue($col['type'], $_value);
300
301
                    if ($col['id'] == 'ga:continent') {
302
                        $value = Plugin::$plugin->geo->getContinentCode($value);
303
                    }
304
305
                    if ($col['id'] == 'ga:subContinent') {
306
                        $value = Plugin::$plugin->geo->getSubContinentCode($value);
307
                    }
308
309
                    // translate values
310
                    switch ($col['id']) {
311
                        case 'ga:country':
312
                        case 'ga:city':
313
                            // case 'ga:continent':
314
                            // case 'ga:subContinent':
315
                        case 'ga:userType':
316
                        case 'ga:javaEnabled':
317
                        case 'ga:deviceCategory':
318
                        case 'ga:mobileInputSelector':
319
                        case 'ga:channelGrouping':
320
                        case 'ga:medium':
321
                            $value = Craft::t('analytics', $value);
322
                            break;
323
                    }
324
325
                    // update cell
326
                    $rows[$kRow][$_valueKey] = $value;
327
                }
328
            }
329
        }
330
331
        return $rows;
332
    }
333
334
    /**
335
     * Format RAW value
336
     *
337
     * @param string $type
338
     * @param string $value
339
     *
340
     * @return float|string
341
     */
342
    private function formatRawValue($type, $value)
343
    {
344
        switch ($type) {
345
            case 'integer':
346
            case 'currency':
347
            case 'float':
348
            case 'time':
349
            case 'percent':
350
                return (float)$value;
351
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
352
353
            default:
354
                return (string)$value;
355
        }
356
    }
357
}
358