Passed
Push — v4 ( 0ba6fc...f4ca6e )
by Benjamin
04:02
created

ReportsController::getRealtimeDemoResponse()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 16
nc 2
nop 0
dl 0
loc 25
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\web\BadRequestHttpException
26
     */
27
    public function actionElement()
28
    {
29
        $elementId = Craft::$app->getRequest()->getRequiredParam('elementId');
30
        $siteId = (int) Craft::$app->getRequest()->getRequiredParam('siteId');
31
        $metric = Craft::$app->getRequest()->getRequiredParam('metric');
32
33
        $response = Analytics::$plugin->getReports()->getElementReport($elementId, $siteId, $metric);
34
35
        return $this->asJson([
36
            'type' => 'area',
37
            'chart' => $response
38
        ]);
39
    }
40
41
    /**
42
     * Get realtime widget report.
43
     *
44
     * @return Response
45
     */
46
    public function actionRealtimeWidget()
47
    {
48
        if(Analytics::$plugin->getSettings()->demoMode) {
49
            return $this->getRealtimeDemoResponse();
50
        }
51
52
53
        // Active users
54
        
55
        $activeUsers = 0;
56
57
        $viewId = Craft::$app->getRequest()->getBodyParam('viewId');
58
59
        $request = [
60
            'viewId' => $viewId,
61
            'metrics' => 'ga:activeVisitors',
62
            'optParams' => []
63
        ];
64
65
        $response = Analytics::$plugin->getReports()->getRealtimeReport($request);
66
67
        if (!empty($response['totalsForAllResults']) && isset($response['totalsForAllResults']['ga:activeVisitors'])) {
68
            $activeUsers = $response['totalsForAllResults']['ga:activeVisitors'];
69
        }
70
71
72
73
        // Pageviews
74
75
        $pageviewsRequest = [
76
            'viewId' => $viewId,
77
            'metrics' => 'rt:pageviews',
78
            'optParams' => ['dimensions' => 'rt:minutesAgo']
79
        ];
80
81
        $pageviews = Analytics::$plugin->getReports()->getRealtimeReport($pageviewsRequest);
82
83
84
        // Active pages
85
86
        $activePagesRequest = [
87
            'viewId' => $viewId,
88
            'metrics' => 'rt:activeUsers',
89
            'optParams' => ['dimensions' => 'rt:pagePath', 'max-results' => 5]
90
        ];
91
92
        $activePages = Analytics::$plugin->getReports()->getRealtimeReport($activePagesRequest);
93
94
        return $this->asJson([
95
            'activeUsers' => $activeUsers,
96
            'pageviews' => $pageviews,
97
            'activePages' => $activePages,
98
        ]);
99
    }
100
101
    /**
102
     * Get report widget report.
103
     *
104
     * @return Response
105
     * @throws InvalidChartTypeException
106
     */
107
    public function actionReportWidget()
108
    {
109
        $viewId = Craft::$app->getRequest()->getBodyParam('viewId');
110
        $chart = Craft::$app->getRequest()->getBodyParam('chart');
111
        $period = Craft::$app->getRequest()->getBodyParam('period');
112
        $options = Craft::$app->getRequest()->getBodyParam('options');
113
114
        $request = [
115
            'viewId' => $viewId,
116
            'chart' => $chart,
117
            'period' => $period,
118
            'options' => $options,
119
        ];
120
121
        $cacheId = ['getReport', $request];
122
123
        $response = Analytics::$plugin->cache->get($cacheId);
124
125
        if (!$response) {
126
            switch ($chart) {
127
                case 'area':
128
                    $response = Analytics::$plugin->getReports()->getAreaReport($request);
129
                    break;
130
                case 'counter':
131
                    $response = Analytics::$plugin->getReports()->getCounterReport($request);
132
                    break;
133
                case 'pie':
134
                    $response = Analytics::$plugin->getReports()->getPieReport($request);
135
                    break;
136
                case 'table':
137
                    $response = Analytics::$plugin->getReports()->getTableReport($request);
138
                    break;
139
                case 'geo':
140
                    $response = Analytics::$plugin->getReports()->getGeoReport($request);
141
                    break;
142
                default:
143
                    throw new InvalidChartTypeException("Chart type `".$chart."` not supported.");
144
            }
145
146
            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...
147
                Analytics::$plugin->cache->set($cacheId, $response);
148
            }
149
        }
150
151
        return $this->asJson($response);
152
    }
153
154
    // Private Methods
155
    // =========================================================================
156
157
    /**
158
     * Get realtime demo response.
159
     * 
160
     * @return Response
161
     */
162
    private function getRealtimeDemoResponse(): Response
163
    {
164
        $activeUsers = random_int(0, 20);
165
        $pageviews = [
166
            'rows' => []
167
        ];
168
169
        for($i = 0; $i <= 30; $i++) {
170
            $pageviews['rows'][] = [$i, random_int(0, 20)];
171
        }
172
173
        $activePages = [
174
            'rows' => [
175
                ['/some-url/', random_int(0, 20)],
176
                ['/some-super-long-url/with-kebab-case/', random_int(0, 20)],
177
                ['/somesuperlongurlwithoutkebabcasebutstillsuperlong/', random_int(10000000, 20000000)],
178
                ['/someothersuperlongurl/withoutkebabcasebutstillsuperlong/', random_int(0, 20)],
179
                ['/one-last-url/', random_int(0, 20)],
180
            ]
181
        ];
182
183
        return $this->asJson([
184
            'activeUsers' => $activeUsers,
185
            'pageviews' => $pageviews,
186
            'activePages' => $activePages,
187
        ]);
188
    }
189
}
190