Completed
Push — master ( 3e2e54...3d8e82 )
by Freek
01:13
created

Analytics::fetchUserTypes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 17
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 9
nc 1
nop 1
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 View Code Duplication
    public function fetchVisitorsAndPageViews(Period $period): 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...
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 View Code Duplication
    public function fetchTotalVisitorsAndPageViews(Period $period): 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...
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 View Code Duplication
    public function fetchMostVisitedPages(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...
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
    /**
173
     * Call the query method on the authenticated client.
174
     *
175
     * @param Period $period
176
     * @param string $metrics
177
     * @param array  $others
178
     *
179
     * @return array|null
180
     */
181
    public function performQuery(Period $period, string $metrics, array $others = [])
182
    {
183
        return $this->client->performQuery(
184
            $this->viewId,
185
            $period->startDate,
186
            $period->endDate,
187
            $metrics,
188
            $others
189
        );
190
    }
191
192
    /*
193
     * Get the underlying Google_Service_Analytics object. You can use this
194
     * to basically call anything on the Google Analytics API.
195
     */
196
    public function getAnalyticsService(): Google_Service_Analytics
197
    {
198
        return $this->client->getAnalyticsService();
199
    }
200
}
201