Completed
Push — administration ( 340be6 )
by Fèvre
13:29
created

PageController::index()   F

Complexity

Conditions 14
Paths 672

Size

Total Lines 183
Code Lines 125

Duplication

Lines 23
Ratio 12.57 %

Importance

Changes 0
Metric Value
dl 23
loc 183
rs 2.4369
c 0
b 0
f 0
cc 14
eloc 125
nc 672
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Xetaravel\Http\Controllers\Admin;
3
4
use Carbon\Carbon;
5
use Illuminate\Http\Request;
6
use Rinvex\Country\CountryLoader;
7
use Spatie\Analytics\AnalyticsFacade;
8
use Spatie\Analytics\Period;
9
10
class PageController extends Controller
11
{
12
    /**
13
     * Show the application dashboard.
14
     *
15
     * @return \Illuminate\Http\Response
0 ignored issues
show
Documentation introduced by
Should the return type not be \Illuminate\View\View|\I...\Contracts\View\Factory?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
16
     */
17
    public function index()
18
    {
19
        // Visitors
20
        $startDate = Carbon::now()->subDays(7);
21
        $endDate = Carbon::now()->subDay();
22
        $visitorsData = AnalyticsFacade::performQuery(
23
            Period::create($startDate, $endDate),
24
            'ga:sessions,ga:pageviews',
25
            [
26
                'dimensions' => 'ga:date',
27
                'sort' => 'ga:date'
28
            ]
29
        );
30
31
        $data = [];
32
        foreach ($visitorsData->rows as $row) {
33
            $row[0] = Carbon::createFromFormat('Ymd', $row[0]);
34
35
            array_push($data, $row);
36
        }
37
        $visitorsData->rows = array_reverse($data);
38
39
        // Browsers
40
        $startDate = Carbon::create(2014, 07, 01);
41
        $browsersData = AnalyticsFacade::performQuery(
42
            Period::create($startDate, $endDate),
43
            'ga:pageviews',
44
            [
45
                'dimensions' => 'ga:browser',
46
                'sort' => 'ga:pageviews',
47
                'filters' => 'ga:browser==Chrome,'
48
                    .'ga:browser==Firefox,'
49
                    .'ga:browser==Internet Explorer,'
50
                    .'ga:browser==Safari,'
51
                    .'ga:browser==Opera'
52
            ]
53
        );
54
55
        $data = [];
56
        foreach ($browsersData->rows as $browser) {
57
            $percent = round(($browser[1] * 100) / $browsersData->totalsForAllResults['ga:pageviews'], 1);
58
59
            switch ($browser[0]) {
60
                case 'Chrome':
61
                    $color = '#00acac';
62
                    break;
63
                case 'Firefox':
64
                    $color = '#f4645f';
65
                    break;
66
                case 'Safari':
67
                    $color = '#727cb6';
68
                    break;
69
                case 'Opera':
70
                    $color = '#348fe2';
71
                    break;
72
                case 'Internet Explorer':
73
                    $color = '#75e376';
74
                    break;
75
                default:
76
                    $color = '#ddd';
77
            }
78
79
            $browser[] = $percent;
80
            $browser[] = $color;
81
82
            array_push($data, $browser);
83
        }
84
        $browsersData->rows = array_reverse($data);
85
86
        // Countries
87
        $countriesData = AnalyticsFacade::performQuery(
88
            Period::create($startDate, $endDate),
89
            'ga:pageviews,ga:sessions',
90
            [
91
                'dimensions' => 'ga:countryIsoCode',
92
                'sort' => '-ga:pageviews'
93
            ]
94
        );
95
96
        foreach ($countriesData->rows as $country) {
97
            $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...
98
                'ga:pageviews' => $country[1],
99
                'ga:sessions' => $country[2],
100
                'percent' => round(($country[1] * 100) / $countriesData->totalsForAllResults['ga:pageviews'], 1)
101
            ];
102
103
            if (!in_array($country[0], ['ZZ'])) {
104
                $countryInstance = country((string)strtolower($country[0]));
105
                $countries[$country[0]] += [
106
                    'countryName' => $countryInstance->getName()
107
                ];
108
            } else {
109
                $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...
110
                    'countryName' => 'Unknown'
111
                ];
112
            }
113
        }
114
        $countriesData->rows = $countries;
115
        $topCountries = array_slice($countries, 0, 3);
116
117
        // Devices
118
        $startDate = Carbon::now()->subMonths(7);
119
        $devicesData = AnalyticsFacade::performQuery(
120
            Period::create($startDate, $endDate),
121
            'ga:pageviews',
122
            [
123
                'dimensions' => 'ga:mobileDeviceBranding,ga:yearMonth',
124
                'sort' => '-ga:mobileDeviceBranding',
125
                'filters' => 'ga:mobileDeviceBranding==Apple,'
126
                    .'ga:mobileDeviceBranding==Samsung,'
127
                    .'ga:mobileDeviceBranding==Google,'
128
                    .'ga:mobileDeviceBranding==HTC,'
129
                    .'ga:mobileDeviceBranding==Microsoft'
130
            ]
131
        );
132
133
        $devicesGraph = [];
134 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...
135
            $date = Carbon::now()->subMonths($i);
136
137
            $devicesGraph[$date->format('Ym')] = [
138
                'period' => $date->format('Y-m-d'),
139
                'Apple' => 0,
140
                'Samsung' => 0,
141
                'Google' => 0,
142
                'HTC' => 0,
143
                'Microsoft' => 0
144
            ];
145
        }
146
147
        foreach ($devicesData->rows as $device) {
148
            $devicesGraph[$device[1]][$device[0]] = $device[2];
149
        }
150
        $devicesGraph = array_reverse($devicesGraph);
151
        $devicesGraph = collect($devicesGraph)->toJson();
152
153
        // Operating System
154
        $startDate = Carbon::now()->subMonths(7);
155
        $operatingSystemData = AnalyticsFacade::performQuery(
156
            Period::create($startDate, $endDate),
157
            'ga:pageviews',
158
            [
159
                'dimensions' => 'ga:operatingSystem,ga:yearMonth',
160
                'sort' => '-ga:operatingSystem',
161
                'filters' => 'ga:operatingSystem==Windows,'
162
                    .'ga:operatingSystem==Macintosh,'
163
                    .'ga:operatingSystem==Linux,'
164
                    .'ga:operatingSystem==(not set)'
165
            ]
166
        );
167
168
        $operatingSystemGraph = [];
169 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...
170
            $date = Carbon::now()->subMonths($i);
171
172
            $operatingSystemGraph[$date->format('Ym')] = [
173
                'period' => $date->format('Y-m-d'),
174
                'Windows' => 0,
175
                'Macintosh' => 0,
176
                'Linux' => 0,
177
                '(not set)' => 0
178
            ];
179
        }
180
181
        foreach ($operatingSystemData->rows as $os) {
182
            $operatingSystemGraph[$os[1]][$os[0]] = $os[2];
183
        }
184
        $operatingSystemGraph = array_reverse($operatingSystemGraph);
185
        $operatingSystemGraph = collect($operatingSystemGraph)->toJson();
186
187
        return view(
188
            'Admin::page.index',
189
            [
190
                'breadcrumbs' => $this->breadcrumbs,
0 ignored issues
show
Bug introduced by
The property breadcrumbs does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
191
                'visitorsData' => $visitorsData,
192
                'browsersData' => $browsersData,
193
                'countriesData' => $countriesData,
194
                'topCountries' => $topCountries,
195
                'devicesGraph' => $devicesGraph,
196
                'operatingSystemGraph' => $operatingSystemGraph
197
            ]
198
        );
199
    }
200
}
201