Completed
Pull Request — master (#75)
by Carlos
02:27
created

Analytics::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
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
	use Macroable;
12
13
	/** @var \Spatie\Analytics\AnalyticsClient */
14
	protected $client;
15
16
	/** @var string */
17
	protected $viewId;
18
19
	/**
20
	 * @param \Spatie\Analytics\AnalyticsClient $client
21
	 * @param string                            $viewId
22
	 */
23
	public function __construct(AnalyticsClient $client, $viewId) {
24
		$this->client = $client;
25
26
		$this->viewId = $viewId;
27
	}
28
29
	/**
30
	 * @param string $viewId
31
	 *
32
	 * @return $this
33
	 */
34
	public function setViewId($viewId) {
35
		$this->viewId = $viewId;
36
37
		return $this;
38
	}
39
40
	public function fetchVisitorsAndPageViews(Period $period) {
41
		$response = $this->performQuery(
42
			$period,
43
			'ga:users,ga:pageviews',
44
			['dimensions' => 'ga:date,ga:pageTitle']
45
		);
46
47
		return collect(isset($response['rows']) ? $response['rows'] : [])->map(function (array $dateRow) {
48
			return [
49
				'date' => Carbon::createFromFormat('Ymd', $dateRow[0]),
50
				'pageTitle' => $dateRow[1],
51
				'visitors' => (int) $dateRow[2],
52
				'pageViews' => (int) $dateRow[3],
53
			];
54
		});
55
	}
56
57 View Code Duplication
	public function fetchMostVisitedPages(Period $period = null, $maxResults = 20) {
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
		$response = $this->performQuery(
59
			$period,
0 ignored issues
show
Bug introduced by
It seems like $period defined by parameter $period on line 57 can be null; however, Spatie\Analytics\Analytics::performQuery() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
60
			'ga:pageviews',
61
			[
62
				'dimensions' => 'ga:pagePath,ga:pageTitle',
63
				'sort' => '-ga:pageviews',
64
				'max-results' => $maxResults,
65
			]
66
		);
67
68
		return collect($response['rows'] ?: [])
69
			->map(function (array $pageRow) {
70
				return [
71
					'url' => $pageRow[0],
72
					'pageTitle' => $pageRow[1],
73
					'pageViews' => (int) $pageRow[2],
74
				];
75
			});
76
	}
77
78 View Code Duplication
	public function fetchTopReferrers(Period $period, $maxResults = 20) {
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
		$response = $this->performQuery($period,
80
			'ga:pageviews',
81
			[
82
				'dimensions' => 'ga:fullReferrer',
83
				'sort' => '-ga:pageviews',
84
				'max-results' => $maxResults,
85
			]
86
		);
87
88
		return collect(isset($response['rows']) ? $response['rows'] : [])->map(function (array $pageRow) {
89
			return [
90
				'url' => $pageRow[0],
91
				'pageViews' => (int) $pageRow[1],
92
			];
93
		});
94
	}
95
96
	public function fetchTopBrowsers(Period $period, $maxResults = 10) {
97
		$response = $this->performQuery(
98
			$period,
99
			'ga:sessions',
100
			[
101
				'dimensions' => 'ga:browser',
102
				'sort' => '-ga:sessions',
103
			]
104
		);
105
106
		$topBrowsers = collect(isset($response['rows']) ? $response['rows'] : [])->map(function (array $browserRow) {
107
			return [
108
				'browser' => $browserRow[0],
109
				'sessions' => (int) $browserRow[1],
110
			];
111
		});
112
113
		if ($topBrowsers->count() <= $maxResults) {
114
			return $topBrowsers;
115
		}
116
117
		return $this->summarizeTopBrowsers($topBrowsers, $maxResults);
118
	}
119
120
	protected function summarizeTopBrowsers(Collection $topBrowsers, $maxResults) {
121
		return $topBrowsers
122
			->take($maxResults - 1)
123
			->push([
124
				'browser' => 'Others',
125
				'sessions' => $topBrowsers->splice($maxResults - 1)->sum('sessions'),
126
			]);
127
	}
128
129
	/**
130
	 * Call the query method on the authenticated client.
131
	 *
132
	 * @param Period $period
133
	 * @param string $metrics
134
	 * @param array  $others
135
	 *
136
	 * @return array|null
137
	 */
138
	public function performQuery(Period $period, $metrics, array $others = []) {
139
		return $this->client->performQuery(
140
			$this->viewId,
141
			$period->startDate,
142
			$period->endDate,
143
			$metrics,
144
			$others
145
		);
146
	}
147
148
	/**
149
	 * Get the underlying Google_Service_Analytics object. You can use this
150
	 * to basically call anything on the Google Analytics API.
151
	 *
152
	 * @return \Google_Service_Analytics
153
	 */
154
	public function getAnalyticsService() {
155
		return $this->client->getAnalyticsService();
156
	}
157
}
158