Completed
Push — master ( 0a2a1f...860620 )
by Freek
02:16
created

Analytics::fetchTopBrowsers()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 24
rs 8.9713
cc 2
eloc 13
nc 2
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 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']
49
        );
50
51
        return collect($response['rows'] ?? [])->map(function (array $dateRow) {
52
            return [
53
                'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
54
                'visitors' => (int) $dateRow[1],
55
                'pageViews' => (int) $dateRow[2],
56
            ];
57
        });
58
    }
59
60 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...
61
    {
62
        $response = $this->performQuery(
63
            $period,
64
            'ga:pageviews',
65
            [
66
                'dimensions' => 'ga:pagePath',
67
                'sort' => '-ga:pageviews',
68
                'max-results' => $maxResults,
69
            ]
70
        );
71
72
        return collect($response['rows'] ?? [])
73
            ->map(function (array $pageRow) {
74
                return [
75
                    'url' => $pageRow[0],
76
                    'pageViews' => (int) $pageRow[1],
77
                ];
78
            });
79
    }
80
81 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...
82
    {
83
        $response = $this->performQuery($period,
84
            'ga:pageviews',
85
            [
86
                'dimensions' => 'ga:fullReferrer',
87
                'sort' => '-ga:pageviews',
88
                'max-results' => $maxResults,
89
            ]
90
        );
91
92
        return collect($response['rows'] ?? [])->map(function (array $pageRow) {
93
            return [
94
                'url' => $pageRow[0],
95
                'pageViews' => (int) $pageRow[1],
96
            ];
97
        });
98
    }
99
100
    public function fetchTopBrowsers(Period $period, int $maxResults = 10): Collection
101
    {
102
        $response = $this->performQuery(
103
            $period,
104
            'ga:sessions',
105
            [
106
                'dimensions' => 'ga:browser',
107
                'sort' => '-ga:sessions',
108
            ]
109
        );
110
111
        $topBrowsers = collect($response['rows'] ?? [])->map(function (array $browserRow) {
112
            return [
113
                'browser' => $browserRow[0],
114
                'sessions' => (int) $browserRow[1],
115
            ];
116
        });
117
118
        if ($topBrowsers->count() <= $maxResults) {
119
            return $topBrowsers;
120
        }
121
122
        return $this->summarizeTopBrowsers($topBrowsers, $maxResults);
123
    }
124
125
    protected function summarizeTopBrowsers(Collection $topBrowsers, int $maxResults): Collection
126
    {
127
        return $topBrowsers
128
            ->take($maxResults - 1)
129
            ->push([
130
                'browser' => 'Others',
131
                'sessions' => $topBrowsers->splice($maxResults - 1)->sum('sessions'),
132
            ]);
133
    }
134
135
    /**
136
     * Call the query method on the authenticated client.
137
     *
138
     * @param Period $period
139
     * @param string $metrics
140
     * @param array  $others
141
     *
142
     * @return array|null
143
     */
144
    public function performQuery(Period $period, string $metrics, array $others = [])
145
    {
146
        return $this->client->performQuery(
147
            $this->viewId,
148
            $period->startDate,
149
            $period->endDate,
150
            $metrics,
151
            $others
152
        );
153
    }
154
155
    /**
156
     * Get the underlying Google_Service_Analytics object. You can use this
157
     * to basically call anything on the Google Analytics API.
158
     *
159
     * @return \Google_Service_Analytics
160
     */
161
    public function getAnalyticsService(): Google_Service_Analytics
162
    {
163
        return $this->client->getAnalyticsService();
164
    }
165
}
166