Completed
Pull Request — master (#229)
by
unknown
02:13
created

Analytics::fetchUserTypes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
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
        $userSessions = collect($response->rows ?? [])->map(function (array $usRow) {
130
            return [
131
                'type' => $usRow[0],
132
                'sessions' => (int) $usRow[1],
133
            ];
134
        });
135
136
        return $userSessions;
137
    }
138
139
    public function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection
140
    {
141
        $response = $this->performQuery(
142
            $period,
143
            'ga:sessions',
144
            [
145
                'dimensions' => 'ga:browser',
146
                'sort' => '-ga:sessions',
147
            ]
148
        );
149
150
        $topBrowsers = collect($response['rows'] ?? [])->map(function (array $browserRow) {
151
            return [
152
                'browser' => $browserRow[0],
153
                'sessions' => (int) $browserRow[1],
154
            ];
155
        });
156
157
        if ($topBrowsers->count() <= $maxResults) {
158
            return $topBrowsers;
159
        }
160
161
        return $this->summarizeTopBrowsers($topBrowsers, $maxResults);
162
    }
163
164
    protected function summarizeTopBrowsers(Collection $topBrowsers, int $maxResults): Collection
165
    {
166
        return $topBrowsers
167
            ->take($maxResults - 1)
168
            ->push([
169
                'browser' => 'Others',
170
                'sessions' => $topBrowsers->splice($maxResults - 1)->sum('sessions'),
171
            ]);
172
    }
173
174
    /**
175
     * Call the query method on the authenticated client.
176
     *
177
     * @param Period $period
178
     * @param string $metrics
179
     * @param array  $others
180
     *
181
     * @return array|null
182
     */
183
    public function performQuery(Period $period, string $metrics, array $others = [])
184
    {
185
        return $this->client->performQuery(
186
            $this->viewId,
187
            $period->startDate,
188
            $period->endDate,
189
            $metrics,
190
            $others
191
        );
192
    }
193
194
    /*
195
     * Get the underlying Google_Service_Analytics object. You can use this
196
     * to basically call anything on the Google Analytics API.
197
     */
198
    public function getAnalyticsService(): Google_Service_Analytics
199
    {
200
        return $this->client->getAnalyticsService();
201
    }
202
}
203