Passed
Push — master ( 384962...a2213c )
by Benjamin
26:55 queued 19:06
created

Analytics::getColumns()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link      https://dukt.net/analytics/
4
 * @copyright Copyright (c) 2018, 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()
50
    {
51
        $apiAccounts = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_accounts->listManagementAccounts();
52
        $accounts = $apiAccounts->toSimpleObject()->items;
53
54
        $apiProperties = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_webproperties->listManagementWebproperties('~all');
55
        $properties = $apiProperties->toSimpleObject()->items;
56
57
        $apiViews = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_profiles->listManagementProfiles('~all', '~all');
58
        $views = $apiViews->toSimpleObject()->items;
59
60
        return [
61
            'accounts' => $accounts,
62
            'properties' => $properties,
63
            'views' => $views,
64
        ];
65
    }
66
67
    /**
68
     * Populate Account Explorer Settings
69
     *
70
     * @param array $settings
71
     *
72
     * @return array
73
     * @throws \yii\base\InvalidConfigException
74
     */
75
    public function populateAccountExplorerSettings($settings = [])
76
    {
77
        if (!empty($settings['accountId']) && !empty($settings['webPropertyId']) && !empty($settings['profileId'])) {
78
            $apiAccounts = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_accounts->listManagementAccounts();
79
80
            $account = null;
81
82
            foreach ($apiAccounts as $apiAccount) {
83
                if ($apiAccount->id == $settings['accountId']) {
84
                    $account = $apiAccount;
85
                }
86
            }
87
88
            $webProperty = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_webproperties->get($settings['accountId'], $settings['webPropertyId']);
89
            $profile = Plugin::$plugin->getApis()->getAnalytics()->getService()->management_profiles->get($settings['accountId'], $settings['webPropertyId'], $settings['profileId']);
90
91
            $settings['accountName'] = $account->name;
92
            $settings['webPropertyName'] = $webProperty->name;
93
            $settings['internalWebPropertyId'] = $webProperty->internalWebPropertyId;
94
            $settings['profileCurrency'] = $profile->currency;
95
            $settings['profileName'] = $profile->name;
96
        }
97
98
        return $settings;
99
    }
100
101
    /**
102
     * Parse Report Response
103
     *
104
     * @param $data
105
     *
106
     * @return array
107
     */
108
    public function parseReportResponse($data): array
109
    {
110
        $cols = $this->parseReportResponseCols($data);
111
        $rows = $this->parseReportResponseRows($data, $cols);
112
113
        return [
114
            'cols' => $cols,
115
            'rows' => $rows
116
        ];
117
    }
118
119
    // Private Methods
120
    // =========================================================================
121
122
    /**
123
     * @param array $data
124
     * @return array
125
     */
126
    private function parseReportResponseCols(array $data): array
127
    {
128
        $cols = [];
129
130
        foreach ($data['columnHeaders'] as $col) {
131
            $dataType = $col->dataType;
132
            $id = $col->name;
133
            $label = Plugin::$plugin->metadata->getDimMet($col->name);
134
            $type = strtolower($dataType);
135
136
            switch ($col->name) {
137
                case 'ga:date':
138
                case 'ga:yearMonth':
139
                    $type = 'date';
140
                    break;
141
142
                case 'ga:continent':
143
                    $type = 'continent';
144
                    break;
145
                case 'ga:subContinent':
146
                    $type = 'subContinent';
147
                    break;
148
149
                case 'ga:latitude':
150
                case 'ga:longitude':
151
                    $type = 'float';
152
                    break;
153
            }
154
155
            $cols[] = [
156
                'type' => $type,
157
                'dataType' => $dataType,
158
                'id' => $id,
159
                'label' => Craft::t('analytics', $label),
160
            ];
161
        }
162
163
        return $cols;
164
    }
165
166
    /**
167
     * @param array $data
168
     * @param array $cols
169
     * @return array
170
     */
171
    private function parseReportResponseRows(array $data, array $cols): array
172
    {
173
        $rows = [];
174
175
        if ($data['rows']) {
176
            $rows = $data->rows;
177
178
            foreach ($rows as $kRow => $row) {
179
                foreach ($row as $_valueKey => $_value) {
180
                    $col = $cols[$_valueKey];
181
182
                    $value = $this->formatRawValue($col['type'], $_value);
183
184
                    if ($col['id'] == 'ga:continent') {
185
                        $value = Plugin::$plugin->geo->getContinentCode($value);
186
                    }
187
188
                    if ($col['id'] == 'ga:subContinent') {
189
                        $value = Plugin::$plugin->geo->getSubContinentCode($value);
190
                    }
191
192
                    // translate values
193
                    switch ($col['id']) {
194
                        case 'ga:country':
195
                        case 'ga:city':
196
                            // case 'ga:continent':
197
                            // case 'ga:subContinent':
198
                        case 'ga:userType':
199
                        case 'ga:javaEnabled':
200
                        case 'ga:deviceCategory':
201
                        case 'ga:mobileInputSelector':
202
                        case 'ga:channelGrouping':
203
                        case 'ga:medium':
204
                            $value = Craft::t('analytics', $value);
205
                            break;
206
                    }
207
208
                    // update cell
209
                    $rows[$kRow][$_valueKey] = $value;
210
                }
211
            }
212
        }
213
214
        return $rows;
215
    }
216
217
    /**
218
     * Format RAW value
219
     *
220
     * @param string $type
221
     * @param string $value
222
     *
223
     * @return float|string
224
     */
225
    private function formatRawValue($type, $value)
226
    {
227
        switch ($type) {
228
            case 'integer':
229
            case 'currency':
230
            case 'float':
231
            case 'time':
232
            case 'percent':
233
                return (float)$value;
234
                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...
235
236
            default:
237
                return (string)$value;
238
        }
239
    }
240
}
241