Completed
Push — master ( c9eaa9...6356b7 )
by Rias
24:09 queued 19s
created

Analytics::getViewId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 getViewId()
44
    {
45
        return $this->viewId;
46
    }
47
48 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...
49
    {
50
        $response = $this->performQuery(
51
            $period,
52
            'ga:users,ga:pageviews',
53
            ['dimensions' => 'ga:date,ga:pageTitle']
54
        );
55
56
        return collect($response['rows'] ?? [])->map(function (array $dateRow) {
57
            return [
58
                'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
59
                'pageTitle' => $dateRow[1],
60
                'visitors' => (int) $dateRow[2],
61
                'pageViews' => (int) $dateRow[3],
62
            ];
63
        });
64
    }
65
66 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...
67
    {
68
        $response = $this->performQuery(
69
            $period,
70
            'ga:users,ga:pageviews',
71
            ['dimensions' => 'ga:date']
72
        );
73
74
        return collect($response['rows'] ?? [])->map(function (array $dateRow) {
75
            return [
76
                'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
77
                'visitors' => (int) $dateRow[1],
78
                'pageViews' => (int) $dateRow[2],
79
            ];
80
        });
81
    }
82
83 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...
84
    {
85
        $response = $this->performQuery(
86
            $period,
87
            'ga:pageviews',
88
            [
89
                'dimensions' => 'ga:pagePath,ga:pageTitle',
90
                'sort' => '-ga:pageviews',
91
                'max-results' => $maxResults,
92
            ]
93
        );
94
95
        return collect($response['rows'] ?? [])
96
            ->map(function (array $pageRow) {
97
                return [
98
                    'url' => $pageRow[0],
99
                    'pageTitle' => $pageRow[1],
100
                    'pageViews' => (int) $pageRow[2],
101
                ];
102
            });
103
    }
104
105 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...
106
    {
107
        $response = $this->performQuery($period,
108
            'ga:pageviews',
109
            [
110
                'dimensions' => 'ga:fullReferrer',
111
                'sort' => '-ga:pageviews',
112
                'max-results' => $maxResults,
113
            ]
114
        );
115
116
        return collect($response['rows'] ?? [])->map(function (array $pageRow) {
117
            return [
118
                'url' => $pageRow[0],
119
                'pageViews' => (int) $pageRow[1],
120
            ];
121
        });
122
    }
123
124
    public function fetchUserTypes(Period $period): Collection
125
    {
126
        $response = $this->performQuery(
127
            $period,
128
            'ga:sessions',
129
            [
130
                'dimensions' => 'ga:userType',
131
            ]
132
        );
133
134
        return collect($response->rows ?? [])->map(function (array $userRow) {
135
            return [
136
                'type' => $userRow[0],
137
                'sessions' => (int) $userRow[1],
138
            ];
139
        });
140
    }
141
142
    public function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection
143
    {
144
        $response = $this->performQuery(
145
            $period,
146
            'ga:sessions',
147
            [
148
                'dimensions' => 'ga:browser',
149
                'sort' => '-ga:sessions',
150
            ]
151
        );
152
153
        $topBrowsers = collect($response['rows'] ?? [])->map(function (array $browserRow) {
154
            return [
155
                'browser' => $browserRow[0],
156
                'sessions' => (int) $browserRow[1],
157
            ];
158
        });
159
160
        if ($topBrowsers->count() <= $maxResults) {
161
            return $topBrowsers;
162
        }
163
164
        return $this->summarizeTopBrowsers($topBrowsers, $maxResults);
165
    }
166
167
    protected function summarizeTopBrowsers(Collection $topBrowsers, int $maxResults): Collection
168
    {
169
        return $topBrowsers
170
            ->take($maxResults - 1)
171
            ->push([
172
                'browser' => 'Others',
173
                'sessions' => $topBrowsers->splice($maxResults - 1)->sum('sessions'),
174
            ]);
175
    }
176
177
    /**
178
     * Call the query method on the authenticated client.
179
     *
180
     * @param Period $period
181
     * @param string $metrics
182
     * @param array  $others
183
     *
184
     * @return array|null
185
     */
186
    public function performQuery(Period $period, string $metrics, array $others = [])
187
    {
188
        return $this->client->performQuery(
189
            $this->viewId,
190
            $period->startDate,
191
            $period->endDate,
192
            $metrics,
193
            $others
194
        );
195
    }
196
197
    /*
198
     * Get the underlying Google_Service_Analytics object. You can use this
199
     * to basically call anything on the Google Analytics API.
200
     */
201
    public function getAnalyticsService(): Google_Service_Analytics
202
    {
203
        return $this->client->getAnalyticsService();
204
    }
205
}
206