Completed
Push — administration ( 67d1c3...18dbd2 )
by Fèvre
05:11 queued 02:35
created

AnalyticsComponent::buildOperatingSytemGraph()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 38
Code Lines 25

Duplication

Lines 11
Ratio 28.95 %

Importance

Changes 0
Metric Value
dl 11
loc 38
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 25
nc 4
nop 0
1
<?php
2
namespace Xetaravel\Http\Components;
3
4
use Carbon\Carbon;
5
use Rinvex\Country\CountryLoader;
6
use Spatie\Analytics\AnalyticsFacade;
7
use Spatie\Analytics\Period;
8
9
trait AnalyticsComponent
10
{
11
    /**
12
     * The and date used in Analytics requests.
13
     *
14
     * @var \Carbon\Carbon
15
     */
16
    protected $endDate;
17
18
    /**
19
     * Build the today visitors metric.
20
     *
21
     * @codeCoverageIgnore
22
     *
23
     * @return string
24
     */
25
    public function buildTodayVisitors(): string
26
    {
27
        $startDate = Carbon::today();
28
        $endDate = Carbon::now();
29
30
        $visitorsData = AnalyticsFacade::performQuery(Period::create($startDate, $endDate), 'ga:users');
31
32
        return $visitorsData->totalsForAllResults['ga:users'];
33
    }
34
35
    /**
36
     * Build the visitors graph for the last 7 days.
37
     *
38
     * @codeCoverageIgnore
39
     *
40
     * @return \Google_Service_Analytics_GaData
41
     */
42
    public function buildVisitorsGraph(): \Google_Service_Analytics_GaData
43
    {
44
        $startDate = Carbon::now()->subDays(7);
45
46
        $visitorsData = AnalyticsFacade::performQuery(
47
            Period::create($startDate, $this->endDate),
48
            'ga:sessions,ga:pageviews',
49
            [
50
                'dimensions' => 'ga:date',
51
                'sort' => 'ga:date'
52
            ]
53
        );
54
55
        $visitorsGraph = [];
56
        foreach ($visitorsData->rows as $row) {
57
            $row[0] = Carbon::createFromFormat('Ymd', $row[0]);
58
59
            array_push($visitorsGraph, $row);
60
        }
61
        $visitorsData->rows = array_reverse($visitorsGraph);
62
63
        return $visitorsData;
64
    }
65
66
    /**
67
     * Build the browsers graph from the beginning.
68
     *
69
     * @codeCoverageIgnore
70
     *
71
     * @return \Google_Service_Analytics_GaData
72
     */
73
    public function buildBrowsersGraph(): \Google_Service_Analytics_GaData
74
    {
75
        $startDate = Carbon::createFromFormat('Y-m-d', config('analytics.start_date'));
76
77
        $browsersData = AnalyticsFacade::performQuery(
78
            Period::create($startDate, $this->endDate),
79
            'ga:pageviews',
80
            [
81
                'dimensions' => 'ga:browser',
82
                'sort' => 'ga:pageviews',
83
                'filters' => 'ga:browser==Chrome,'
84
                    .'ga:browser==Firefox,'
85
                    .'ga:browser==Internet Explorer,'
86
                    .'ga:browser==Safari,'
87
                    .'ga:browser==Opera'
88
            ]
89
        );
90
91
        $browsersGraph = [];
92
        foreach ($browsersData->rows as $browser) {
93
            $browser[] = $this->getPercentage($browser[1], $browsersData->totalsForAllResults['ga:pageviews']);
94
            $browser[] = $this->getBrowserColor($browser[0]);
95
96
            array_push($browsersGraph, $browser);
97
        }
98
        $browsersData->rows = array_reverse($browsersGraph);
99
100
        return $browsersData;
101
    }
102
103
    /**
104
     * Build the countries graph from the beginning.
105
     *
106
     * @codeCoverageIgnore
107
     *
108
     * @return \Google_Service_Analytics_GaData
109
     */
110
    public function buildCountriesGraph(): \Google_Service_Analytics_GaData
111
    {
112
        $startDate = Carbon::createFromFormat('Y-m-d', config('analytics.start_date'));
113
114
        $countriesData = AnalyticsFacade::performQuery(
115
            Period::create($startDate, $this->endDate),
116
            'ga:pageviews,ga:sessions',
117
            [
118
                'dimensions' => 'ga:countryIsoCode',
119
                'sort' => '-ga:pageviews'
120
            ]
121
        );
122
123
        foreach ($countriesData->rows as $country) {
124
            $countries[$country[0]] = [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$countries was never initialized. Although not strictly required by PHP, it is generally a good practice to add $countries = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
125
                'ga:pageviews' => $country[1],
126
                'ga:sessions' => $country[2],
127
                'percent' => $this->getPercentage($country[1], $countriesData->totalsForAllResults['ga:pageviews'])
128
            ];
129
130
            if (!in_array($country[0], ['ZZ'])) {
131
                $countryInstance = country((string)strtolower($country[0]));
132
                $countries[$country[0]] += [
133
                    'countryName' => $countryInstance->getName()
134
                ];
135
            } else {
136
                $countries[$country[0]] += [
0 ignored issues
show
Bug introduced by
The variable $countries does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
137
                    'countryName' => 'Unknown'
138
                ];
139
            }
140
        }
141
        $countriesData->rows = $countries;
142
143
        return $countriesData;
144
    }
145
146
    /**
147
     * Build the devices graph from the last 7 months.
148
     *
149
     * @codeCoverageIgnore
150
     *
151
     * @return string
152
     */
153
    public function buildDevicesGraph(): string
154
    {
155
        $startDate = Carbon::now()->subMonths(7);
156
157
        $devicesData = AnalyticsFacade::performQuery(
158
            Period::create($startDate, $this->endDate),
159
            'ga:pageviews',
160
            [
161
                'dimensions' => 'ga:mobileDeviceBranding,ga:yearMonth',
162
                'sort' => '-ga:mobileDeviceBranding',
163
                'filters' => 'ga:mobileDeviceBranding==Apple,'
164
                    .'ga:mobileDeviceBranding==Samsung,'
165
                    .'ga:mobileDeviceBranding==Google,'
166
                    .'ga:mobileDeviceBranding==HTC,'
167
                    .'ga:mobileDeviceBranding==Microsoft'
168
            ]
169
        );
170
171
        $devicesGraph = [];
172 View Code Duplication
        for ($i = 0; $i < 8; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
173
            $date = Carbon::now()->subMonths($i);
174
175
            $devicesGraph[$date->format('Ym')] = [
176
                'period' => $date->format('Y-m-d'),
177
                'Apple' => 0,
178
                'Samsung' => 0,
179
                'Google' => 0,
180
                'HTC' => 0,
181
                'Microsoft' => 0
182
            ];
183
        }
184
185
        foreach ($devicesData->rows as $device) {
186
            $devicesGraph[$device[1]][$device[0]] = $device[2];
187
        }
188
        $devicesGraph = array_reverse($devicesGraph);
189
        $devicesGraph = collect($devicesGraph)->toJson();
190
191
        return $devicesGraph;
192
    }
193
194
    /**
195
     * Build the operating system graph from the last 7 months.
196
     *
197
     * @codeCoverageIgnore
198
     *
199
     * @return string
200
     */
201
    public function buildOperatingSytemGraph(): string
202
    {
203
        $startDate = Carbon::now()->subMonths(7);
204
205
        $operatingSystemData = AnalyticsFacade::performQuery(
206
            Period::create($startDate, $this->endDate),
207
            'ga:pageviews',
208
            [
209
                'dimensions' => 'ga:operatingSystem,ga:yearMonth',
210
                'sort' => '-ga:operatingSystem',
211
                'filters' => 'ga:operatingSystem==Windows,'
212
                    .'ga:operatingSystem==Macintosh,'
213
                    .'ga:operatingSystem==Linux,'
214
                    .'ga:operatingSystem==(not set)'
215
            ]
216
        );
217
218
        $operatingSystemGraph = [];
219 View Code Duplication
        for ($i = 0; $i < 8; $i++) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
220
            $date = Carbon::now()->subMonths($i);
221
222
            $operatingSystemGraph[$date->format('Ym')] = [
223
                'period' => $date->format('Y-m-d'),
224
                'Windows' => 0,
225
                'Macintosh' => 0,
226
                'Linux' => 0,
227
                '(not set)' => 0
228
            ];
229
        }
230
231
        foreach ($operatingSystemData->rows as $os) {
232
            $operatingSystemGraph[$os[1]][$os[0]] = $os[2];
233
        }
234
        $operatingSystemGraph = array_reverse($operatingSystemGraph);
235
        $operatingSystemGraph = collect($operatingSystemGraph)->toJson();
236
237
        return $operatingSystemGraph;
238
    }
239
240
    /**
241
     * Get the percentage relative to the total page views.
242
     *
243
     * @param int $pageviews The page views.
244
     * @param int $total The total page views.
245
     *
246
     * @return float
247
     */
248
    public function getPercentage($pageviews, $total): float
249
    {
250
        $percentage = ($pageviews * 100) / $total;
251
252
        return round($percentage, 1);
253
    }
254
255
    /**
256
     * Get the browser color by his name
257
     *
258
     * @param string $browser The name of the browser.
259
     *
260
     * @return string
261
     */
262
    public function getBrowserColor(string $browser): string
263
    {
264
        switch ($browser) {
265
            case 'Chrome':
266
                $color = '#00acac';
267
                break;
268
            case 'Firefox':
269
                $color = '#f4645f';
270
                break;
271
            case 'Safari':
272
                $color = '#727cb6';
273
                break;
274
            case 'Opera':
275
                $color = '#348fe2';
276
                break;
277
            case 'Internet Explorer':
278
                $color = '#75e376';
279
                break;
280
            default:
281
                $color = '#ddd';
282
        }
283
284
        return $color;
285
    }
286
}
287