Completed
Push — master ( 0b2f36...19d6a1 )
by Freek
08:35
created

Analytics::getAnalyticsService()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Spatie\Analytics;
4
5
use Carbon\Carbon;
6
use DateTime;
7
use Google_Service_Analytics;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Traits\Macroable;
10
11
class Analytics
12
{
13
    use Macroable;
14
15
    /** @var \Spatie\Analytics\AnalyticsClient */
16
    protected $client;
17
18
    /** @var string */
19
    protected $viewId;
20
21
    /**
22
     * @param AnalyticsClient $client
23
     * @param string          $viewId
24
     */
25
    public function __construct(AnalyticsClient $client, string $viewId)
26
    {
27
        $this->client = $client;
28
29
        $this->viewId = $viewId;
30
    }
31
32
    /**
33
     * @param string $viewId
34
     *
35
     * @return $this
36
     */
37
    public function setViewId(string $viewId)
38
    {
39
        $this->viewId = $viewId;
40
41
        return $this;
42
    }
43
44 View Code Duplication
    public function fetchVisitorsAndPageViews(DateTime $startDate, DateTime $endDate): 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...
45
    {
46
        $response = $this->performQuery($startDate, $endDate, 'ga:users,ga:pageviews', ['dimensions' => 'ga:date']);
47
48
        return collect($response['rows'] ?? [])->map(function (array $dateRow) {
49
            return [
50
                'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
51
                'visitors' => (int) $dateRow[1],
52
                'pageViews' => (int) $dateRow[2],
53
            ];
54
        });
55
    }
56
57 View Code Duplication
    public function fetchMostVisitedPages(DateTime $startDate, DateTime $endDate, 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...
58
    {
59
        $response = $this->performQuery($startDate, $endDate, 'ga:pageviews', ['dimensions' => 'ga:pagePath', 'sort' => '-ga:pageviews', 'max-results' => $maxResults]);
60
61
        return collect($response['rows'] ?? [])
62
            ->map(function (array $pageRow) {
63
                return [
64
                    'url' => $pageRow[0],
65
                    'pageViews' => (int) $pageRow[1],
66
                ];
67
            });
68
    }
69
70 View Code Duplication
    public function fetchTopReferrers(DateTime $startDate, DateTime $endDate, 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...
71
    {
72
        $response = $this->performQuery($startDate, $endDate, 'ga:pageviews', ['dimensions' => 'ga:fullReferrer', 'sort' => '-ga:pageviews', 'max-results' => $maxResults]);
73
74
        return collect($response['rows'] ?? [])->map(function (array $pageRow) {
75
            return [
76
                'url' => $pageRow[0],
77
                'pageViews' => (int) $pageRow[1],
78
            ];
79
        });
80
    }
81
82
    public function fetchTopBrowsers(DateTime $startDate, DateTime $endDate, int $maxResults = 10): Collection
83
    {
84
        $response = $this->performQuery($startDate, $endDate, 'ga:sessions', ['dimensions' => 'ga:browser', 'sort' => '-ga:sessions']);
85
86
        $topBrowsers = collect($response['rows'] ?? [])->map(function (array $browserRow) {
87
            return [
88
                'browser' => $browserRow[0],
89
                'sessions' => (int) $browserRow[1],
90
            ];
91
        });
92
93
        if ($topBrowsers->count() <= $maxResults) {
94
            return $topBrowsers;
95
        }
96
97
        return $this->summarizeTopBrowsers($topBrowsers, $maxResults - 1);
98
    }
99
100
    protected function summarizeTopBrowsers(Collection $topBrowsers, int $summarizeAfter)
101
    {
102
        $otherBrowsersRow = $topBrowsers
103
            ->splice($summarizeAfter)
104
            ->reduce(function (array $totals, array $browserRow) {
105
106
                $totals['sessions'] += (int) $browserRow['sessions'];
107
108
                return $totals;
109
            }, ['browser' => 'Others', 'sessions' => 0]);
110
111
        return $topBrowsers
112
            ->take($summarizeAfter)
113
            ->push($otherBrowsersRow);
114
    }
115
116
    /**
117
     * Call the query method on the authenticated client.
118
     *
119
     * @param DateTime $startDate
120
     * @param DateTime $endDate
121
     * @param string   $metrics
122
     * @param array    $others
123
     *
124
     * @return array|null
125
     */
126
    public function performQuery(DateTime $startDate, DateTime $endDate, string $metrics, array $others = [])
127
    {
128
        return $this->client->performQuery(
129
            $this->viewId,
130
            $startDate,
131
            $endDate,
132
            $metrics,
133
            $others
134
        );
135
    }
136
137
    /**
138
     * Get the underlying Google_Service_Analytics object. You can use this
139
     * to basically call anything on the Google Analytics API.
140
     *
141
     * @return \Google_Service_Analytics
142
     */
143
    public function getAnalyticsService(): Google_Service_Analytics
144
    {
145
        return $this->client->getAnalyticsService();
146
    }
147
}
148