Passed
Push — v4 ( ddc255...062845 )
by Benjamin
04:12
created

ReportsController::getRealtimeDemoTestResponse()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 18
nc 4
nop 0
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link      https://dukt.net/craft/analytics/
4
 * @copyright Copyright (c) 2018, Dukt
5
 * @license   https://dukt.net/craft/analytics/docs/license
6
 */
7
8
namespace dukt\analytics\controllers;
9
10
use Craft;
11
use craft\web\Controller;
12
use dukt\analytics\errors\InvalidChartTypeException;
13
use dukt\analytics\Plugin as Analytics;
14
use yii\web\Response;
15
16
class ReportsController extends Controller
17
{
18
    // Public Methods
19
    // =========================================================================
20
21
    /**
22
     * Get element report.
23
     *
24
     * @return Response
25
     * @throws \yii\base\InvalidConfigException
26
     * @throws \yii\web\BadRequestHttpException
27
     */
28
    public function actionElement()
29
    {
30
        $elementId = Craft::$app->getRequest()->getRequiredParam('elementId');
31
        $siteId = (int)Craft::$app->getRequest()->getRequiredParam('siteId');
32
        $metric = Craft::$app->getRequest()->getRequiredParam('metric');
33
34
        $response = Analytics::$plugin->getReports()->getElementReport($elementId, $siteId, $metric);
35
36
        return $this->asJson([
37
            'type' => 'area',
38
            'chart' => $response
39
        ]);
40
    }
41
42
    /**
43
     * Get realtime widget report.
44
     *
45
     * @return Response
46
     * @throws \yii\base\InvalidConfigException
47
     */
48
    public function actionRealtimeWidget()
49
    {
50
        if (Analytics::$plugin->getSettings()->demoMode) {
51
            return $this->getRealtimeDemoResponse();
52
        }
53
54
55
        // Active users
56
57
        $activeUsers = 0;
58
59
        $viewId = Craft::$app->getRequest()->getBodyParam('viewId');
60
61
        $request = [
62
            'viewId' => $viewId,
63
            'metrics' => 'ga:activeVisitors',
64
            'optParams' => []
65
        ];
66
67
        $response = Analytics::$plugin->getReports()->getRealtimeReport($request);
68
69
        if (!empty($response['totalsForAllResults']) && isset($response['totalsForAllResults']['ga:activeVisitors'])) {
70
            $activeUsers = $response['totalsForAllResults']['ga:activeVisitors'];
71
        }
72
73
74
        // Pageviews
75
76
        $pageviewsRequest = [
77
            'viewId' => $viewId,
78
            'metrics' => 'rt:pageviews',
79
            'optParams' => ['dimensions' => 'rt:minutesAgo']
80
        ];
81
82
        $pageviews = Analytics::$plugin->getReports()->getRealtimeReport($pageviewsRequest);
83
84
85
        // Active pages
86
87
        $activePagesRequest = [
88
            'viewId' => $viewId,
89
            'metrics' => 'rt:activeUsers',
90
            'optParams' => ['dimensions' => 'rt:pagePath', 'max-results' => 5]
91
        ];
92
93
        $activePages = Analytics::$plugin->getReports()->getRealtimeReport($activePagesRequest);
94
95
        return $this->asJson([
96
            'activeUsers' => $activeUsers,
97
            'pageviews' => $pageviews,
98
            'activePages' => $activePages,
99
        ]);
100
    }
101
102
    /**
103
     * Get report widget report.
104
     *
105
     * @return Response
106
     * @throws InvalidChartTypeException
107
     * @throws \yii\base\InvalidConfigException
108
     */
109
    public function actionReportWidget()
110
    {
111
        $viewId = Craft::$app->getRequest()->getBodyParam('viewId');
112
        $chart = Craft::$app->getRequest()->getBodyParam('chart');
113
        $period = Craft::$app->getRequest()->getBodyParam('period');
114
        $options = Craft::$app->getRequest()->getBodyParam('options');
115
116
        $request = [
117
            'viewId' => $viewId,
118
            'chart' => $chart,
119
            'period' => $period,
120
            'options' => $options,
121
        ];
122
123
        $cacheId = ['getReport', $request];
124
125
        $response = Analytics::$plugin->cache->get($cacheId);
126
127
        if (!$response) {
128
            switch ($chart) {
129
                case 'area':
130
                    $response = Analytics::$plugin->getReports()->getAreaReport($request);
131
                    break;
132
                case 'counter':
133
                    $response = Analytics::$plugin->getReports()->getCounterReport($request);
134
                    break;
135
                case 'pie':
136
                    $response = Analytics::$plugin->getReports()->getPieReport($request);
137
                    break;
138
                case 'table':
139
                    $response = Analytics::$plugin->getReports()->getTableReport($request);
140
                    break;
141
                case 'geo':
142
                    $response = Analytics::$plugin->getReports()->getGeoReport($request);
143
                    break;
144
                default:
145
                    throw new InvalidChartTypeException('Chart type `'.$chart.'` not supported.');
146
            }
147
148
            if ($response) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $response of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
149
                Analytics::$plugin->cache->set($cacheId, $response);
150
            }
151
        }
152
153
        return $this->asJson($response);
154
    }
155
156
    // Private Methods
157
    // =========================================================================
158
159
    /**
160
     * Get realtime demo response.
161
     *
162
     * @return Response
163
     */
164
    private function getRealtimeDemoResponse(): Response
165
    {
166
        if (Analytics::$plugin->getSettings()->demoMode === 'test') {
167
            return $this->getRealtimeDemoTestResponse();
168
        }
169
170
        $pageviews = [
171
            'rows' => []
172
        ];
173
174
        for ($i = 0; $i <= 30; $i++) {
175
            $pageviews['rows'][] = [$i, random_int(0, 20)];
176
        }
177
178
        $activePages = [
179
            'rows' => [
180
                ['/a-new-toga/', random_int(1, 20)],
181
                ['/parka-with-stripes-on-back/', random_int(1, 20)],
182
                ['/romper-for-a-red-eye/', random_int(1, 20)],
183
                ['/the-fleece-awakens/', random_int(1, 20)],
184
                ['/the-last-knee-high/', random_int(1, 20)],
185
            ]
186
        ];
187
188
        $activeUsers = 0;
189
190
        foreach ($activePages['rows'] as $row) {
191
            $activeUsers += $row[1];
192
        }
193
194
        return $this->asJson([
195
            'activeUsers' => $activeUsers,
196
            'pageviews' => $pageviews,
197
            'activePages' => $activePages,
198
        ]);
199
    }
200
201
    /**
202
     * Get realtime demo test response.
203
     *
204
     * @return Response
205
     */
206
    private function getRealtimeDemoTestResponse(): Response
207
    {
208
        $pageviews = [
209
            'rows' => []
210
        ];
211
212
        for ($i = 0; $i <= 30; $i++) {
213
            $pageviews['rows'][] = [$i, random_int(0, 20)];
214
        }
215
216
        $activePages = [
217
            'rows' => [
218
                ['/some-url/', random_int(1, 20)],
219
                ['/some-super-long-url/with-kebab-case/', random_int(1, 20)],
220
                ['/somesuperlongurlwithoutkebabcasebutstillsuperlong/', random_int(10000000, 20000000)],
221
                ['/someothersuperlongurl/withoutkebabcasebutstillsuperlong/', random_int(1, 20)],
222
                ['/one-last-url/', random_int(1, 20)],
223
            ]
224
        ];
225
226
        $activeUsers = 0;
227
228
        foreach ($activePages['rows'] as $row) {
229
            $activeUsers += $row[1];
230
        }
231
232
        return $this->asJson([
233
            'activeUsers' => $activeUsers,
234
            'pageviews' => $pageviews,
235
            'activePages' => $activePages,
236
        ]);
237
    }
238
}
239