Completed
Pull Request — master (#327)
by
unknown
08:30
created

Analytics::fetchDeviceVisitors()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18

Duplication

Lines 18
Ratio 100 %

Importance

Changes 0
Metric Value
dl 18
loc 18
rs 9.6666
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Spatie\Analytics;
4
5
use Carbon\Carbon;
6
use Google_Service_Analytics;
7
use Illuminate\Support\Collection;
8
use Illuminate\Support\Traits\Macroable;
9
10
class Analytics
11
{
12
    use Macroable;
13
14
    /** @var \Spatie\Analytics\AnalyticsClient */
15
    protected $client;
16
17
    /** @var string */
18
    protected $viewId;
19
20
    /**
21
     * @param \Spatie\Analytics\AnalyticsClient $client
22
     * @param string                            $viewId
23
     */
24
    public function __construct(AnalyticsClient $client, string $viewId)
25
    {
26
        $this->client = $client;
27
28
        $this->viewId = $viewId;
29
    }
30
31
    /**
32
     * @param string $viewId
33
     *
34
     * @return $this
35
     */
36
    public function setViewId(string $viewId)
37
    {
38
        $this->viewId = $viewId;
39
40
        return $this;
41
    }
42
43
    public function fetchVisitorsAndPageViews(Period $period): Collection
44
    {
45
        $response = $this->performQuery(
46
            $period,
47
            'ga:users,ga:pageviews',
48
            ['dimensions' => 'ga:date,ga:pageTitle']
49
        );
50
51
        return collect($response['rows'] ?? [])->map(function (array $dateRow) {
52
            return [
53
                'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
54
                'pageTitle' => $dateRow[1],
55
                'visitors' => (int) $dateRow[2],
56
                'pageViews' => (int) $dateRow[3],
57
            ];
58
        });
59
    }
60
61
    public function fetchTotalVisitorsAndPageViews(Period $period): Collection
62
    {
63
        $response = $this->performQuery(
64
            $period,
65
            'ga:users,ga:pageviews',
66
            ['dimensions' => 'ga:date']
67
        );
68
69
        return collect($response['rows'] ?? [])->map(function (array $dateRow) {
70
            return [
71
                'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
72
                'visitors' => (int) $dateRow[1],
73
                'pageViews' => (int) $dateRow[2],
74
            ];
75
        });
76
    }
77
78
    public function fetchMostVisitedPages(Period $period, int $maxResults = 20): Collection
79
    {
80
        $response = $this->performQuery(
81
            $period,
82
            'ga:pageviews',
83
            [
84
                'dimensions' => 'ga:pagePath,ga:pageTitle',
85
                'sort' => '-ga:pageviews',
86
                'max-results' => $maxResults,
87
            ]
88
        );
89
90
        return collect($response['rows'] ?? [])
91
            ->map(function (array $pageRow) {
92
                return [
93
                    'url' => $pageRow[0],
94
                    'pageTitle' => $pageRow[1],
95
                    'pageViews' => (int) $pageRow[2],
96
                ];
97
            });
98
    }
99
100 View Code Duplication
    public function fetchTopReferrers(Period $period, int $maxResults = 20): Collection
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
    {
102
        $response = $this->performQuery($period,
103
            'ga:pageviews',
104
            [
105
                'dimensions' => 'ga:fullReferrer',
106
                'sort' => '-ga:pageviews',
107
                'max-results' => $maxResults,
108
            ]
109
        );
110
111
        return collect($response['rows'] ?? [])->map(function (array $pageRow) {
112
            return [
113
                'url' => $pageRow[0],
114
                'pageViews' => (int) $pageRow[1],
115
            ];
116
        });
117
    }
118
119
    public function fetchUserTypes(Period $period): Collection
120
    {
121
        $response = $this->performQuery(
122
            $period,
123
            'ga:sessions',
124
            [
125
                'dimensions' => 'ga:userType',
126
            ]
127
        );
128
129
        return collect($response->rows ?? [])->map(function (array $userRow) {
130
            return [
131
                'type' => $userRow[0],
132
                'sessions' => (int) $userRow[1],
133
            ];
134
        });
135
    }
136
137
    public function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection
138
    {
139
        $response = $this->performQuery(
140
            $period,
141
            'ga:sessions',
142
            [
143
                'dimensions' => 'ga:browser',
144
                'sort' => '-ga:sessions',
145
            ]
146
        );
147
148
        $topBrowsers = collect($response['rows'] ?? [])->map(function (array $browserRow) {
149
            return [
150
                'browser' => $browserRow[0],
151
                'sessions' => (int) $browserRow[1],
152
            ];
153
        });
154
155
        if ($topBrowsers->count() <= $maxResults) {
156
            return $topBrowsers;
157
        }
158
159
        return $this->summarizeTopBrowsers($topBrowsers, $maxResults);
160
    }
161
162
    protected function summarizeTopBrowsers(Collection $topBrowsers, int $maxResults): Collection
163
    {
164
        return $topBrowsers
165
            ->take($maxResults - 1)
166
            ->push([
167
                'browser' => 'Others',
168
                'sessions' => $topBrowsers->splice($maxResults - 1)->sum('sessions'),
169
            ]);
170
    }
171
    
172
    // Function to get Visitors Device
173 View Code Duplication
    public function fetchDeviceVisitors(Period $period, int $maxResults = 10): Collection
0 ignored issues
show
Unused Code introduced by
The parameter $maxResults is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
174
    {
175
        $response = $this->performQuery(
176
            $period,
177
            'ga:users',
178
            [
179
                'dimensions' => 'ga:deviceCategory',
180
                'sort' => '-ga:deviceCategory',
181
            ]
182
        );
183
184
        return collect($response->rows ?? [])->map(function (array $userRow) {
185
            return [
186
                'device' => $userRow[0],
187
                'sessions' => (int) $userRow[1],
188
            ];
189
        });
190
    }
191
192
    /**
193
     * Call the query method on the authenticated client.
194
     *
195
     * @param Period $period
196
     * @param string $metrics
197
     * @param array  $others
198
     *
199
     * @return array|null
200
     */
201
    public function performQuery(Period $period, string $metrics, array $others = [])
202
    {
203
        return $this->client->performQuery(
204
            $this->viewId,
205
            $period->startDate,
206
            $period->endDate,
207
            $metrics,
208
            $others
209
        );
210
    }
211
212
    /*
213
     * Get the underlying Google_Service_Analytics object. You can use this
214
     * to basically call anything on the Google Analytics API.
215
     */
216
    public function getAnalyticsService(): Google_Service_Analytics
217
    {
218
        return $this->client->getAnalyticsService();
219
    }
220
}
221