AnalyticsService::topBrowsers()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace Tracking\Services;
4
5
use Carbon\Carbon;
6
use Illuminate\Support\Facades\Schema;
7
use Tracking\Models\Analytics;
8
use function parse_user_agent;
9
10
class AnalyticsService
11
{
12
    public function __construct(Analytics $model)
13
    {
14
        $this->model = $model;
0 ignored issues
show
Bug introduced by
The property model 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...
15
    }
16
17
    public function log($request)
18
    {
19
        $requestData = json_encode(
20
            [
21
            'referer' => $request->server('HTTP_REFERER', null),
22
            'user_agent' => $request->server('HTTP_USER_AGENT', null),
23
            'host' => $request->server('HTTP_HOST', null),
24
            'remote_addr' => $request->server('REMOTE_ADDR', null),
25
            'uri' => $request->server('REQUEST_URI', null),
26
            'method' => $request->server('REQUEST_METHOD', null),
27
            'query' => $request->server('QUERY_STRING', null),
28
            'time' => $request->server('REQUEST_TIME', null),
29
            ]
30
        );
31
32
        if (Schema::hasTable('analytics')) {
33
            $data = [
34
                'data' => $requestData,
35
            ];
36
            if (Schema::hasColumn($this->model->getTable(), 'business_code')) // || Business::isToIgnore())
37
            {
38
                $data['business_code'] = \Business::getCode();
39
            }
40
            $this->model->create(
41
                $data
42
            );
43
        }
44
    }
45
46 View Code Duplication
    public function topReferers($count)
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...
47
    {
48
        $analytics = $this->model->where('created_at', '>', Carbon::now()->subDays($count))->get();
49
        $data = $analytics->pluck('data')->all();
50
51
        return $this->convertDataToItems($data, 'referer', ['unknown' => 0]);
52
    }
53
54 View Code Duplication
    public function topPages($count)
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...
55
    {
56
        $analytics = $this->model->where('created_at', '>', Carbon::now()->subDays($count))->get();
57
        $data = $analytics->pluck('data')->all();
58
59
        return $this->convertDataToItems($data, 'uri');
60
    }
61
62
    public function topBrowsers($count)
63
    {
64
        $analytics = $this->model->where('created_at', '>', Carbon::now()->subDays($count))->get();
65
        $data = $analytics->pluck('data')->all();
66
67
        $browsers = [];
68
69
        foreach ($this->convertDataToItems($data, 'user_agent') as $userAgent => $count) {
70
            $browser = parse_user_agent($userAgent);
0 ignored issues
show
Deprecated Code introduced by
The function parse_user_agent() has been deprecated with message: This exists for backwards compatibility with 0.x and will likely be removed in 2.x

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
71
            $browsers[$browser['browser'].' ('.$browser['version'].') on '.$browser['platform']] = $count;
72
        }
73
74
        return $browsers;
75
    }
76
77
    public function convertDataToItems($data, $key, $conversions = [])
78
    {
79
        if (!isset($conversions['unknown'])) {
80
            $conversions['unknown'] = 0;
81
        }
82
83
        if (!isset($conversions['unknown'])) {
84
            $conversions['unknown'] = 0;
85
        }
86
87
        foreach ($data as $item) {
88
            $visit = json_decode($item);
89
            if (!empty($visit->$key) && $visit->$key > '') {
90
                $conversions[$visit->$key] = 0;
91
            }
92
        }
93
94
        foreach ($data as $item) {
95
            $visit = json_decode($item);
96
            if (!empty($visit->$key) && $visit->$key > '') {
97
                $conversions[$visit->$key] += 1;
98
            } else {
99
                $conversions['unknown'] += 1;
100
            }
101
        }
102
103
        return $conversions;
104
    }
105
106
    public function getDays($count)
107
    {
108
        $analytics = $this->model->where('created_at', '>', Carbon::now()->subDays($count));
109
110
        if ($analytics->first()) {
111
            $endDate = Carbon::now();
112
            $startDate = Carbon::parse($analytics->first()->created_at->format('Y-m-d'));
113
114
            $dateRange = $this->getDateRange($startDate, $endDate);
115
116
            foreach ($dateRange as $date) {
117
                $visits[$date] = $this->model->where('created_at', '>', $date.' 00:00:00')->where('created_at', '<', $date.' 23:59:59')->count();
0 ignored issues
show
Coding Style Comprehensibility introduced by
$visits was never initialized. Although not strictly required by PHP, it is generally a good practice to add $visits = 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...
118
            }
119
120
            $visitCollection = collect($visits);
0 ignored issues
show
Bug introduced by
The variable $visits 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...
121
        } else {
122
            $visitCollection = collect(
123
                [
124
                Carbon::now()->format('Y-m-d') => 0,
125
                ]
126
            );
127
        }
128
129
        return [
130
            'dates' => $visitCollection->keys()->toArray(),
131
            'visits' => $visitCollection->values()->toArray(),
132
        ];
133
    }
134
135
    protected function getDateRange($startDate, $endDate)
136
    {
137
        $dates = [];
138
139
        for ($date = $startDate; $date->lte($endDate); $date->addDay()) {
140
            $dates[] = $date->format('Y-m-d');
141
        }
142
143
        return $dates;
144
    }
145
}
146