CrunchStatistics   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 131
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 9

Importance

Changes 0
Metric Value
wmc 13
lcom 0
cbo 9
dl 0
loc 131
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
C handle() 0 121 13
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Tracking\Jobs;
6
7
use Exception;
8
use UAParser\Parser;
9
use Jenssegers\Agent\Agent;
10
use Illuminate\Bus\Queueable;
11
use Illuminate\Queue\SerializesModels;
12
use Illuminate\Queue\InteractsWithQueue;
13
use Illuminate\Contracts\Queue\ShouldQueue;
14
use Illuminate\Foundation\Bus\Dispatchable;
15
use Illuminate\Http\Request as LaravelRequest;
16
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
17
18
class CrunchStatistics implements ShouldQueue
19
{
20
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
21
22
    /**
23
     * Execute the job.
24
     *
25
     * @return void
26
     */
27
    public function handle(): void
28
    {
29
        app('tracking.statistics.datum')->each(
30
            function ($item) {
31
                try {
32
                    $symfonyRequest = SymfonyRequest::create($item['uri'], $item['server']['REQUEST_METHOD'], $item['input'] ?? [], [], [], $item['server']);
33
                    $symfonyRequest->overrideGlobals();
34
35
                    LaravelRequest::enableHttpMethodParameterOverride();
36
                    $laravelRequest = LaravelRequest::createFromBase($symfonyRequest);
37
                    $laravelRoute = app('router')->getRoutes()->match($laravelRequest);
38
                    $laravelRequest->setRouteResolver(
39
                        function () use ($laravelRoute) {
40
                            return $laravelRoute;
41
                        }
42
                    );
43
44
                    $tokens = [];
45
                    $agent = new Agent($item['server']);
46
                    $UAParser = Parser::create()->parse($agent->getUserAgent());
47
                    $kind = $agent->isDesktop() ? 'desktop' : ($agent->isTablet() ? 'tablet' : ($agent->isPhone() ? 'phone' : ($agent->isRobot() ? 'robot' : 'unknown')));
48
49
                    collect($laravelRequest->route()->getCompiled()->getTokens())->map(
50
                        function ($item) use (&$tokens) {
51
                            return ($item = collect($item)) && $item->contains('variable') ? $tokens[$item[3]] = $item[2] : null;
52
                        }
53
                    );
54
55
                    $route = app('tracking.statistics.route')->firstOrCreate(
56
                        [
57
                        'name' => $laravelRoute->getName(),
58
                        ], [
59
                        'path' => $laravelRoute->uri(),
60
                        'action' => $laravelRoute->getActionName(),
61
                        'middleware' => $laravelRoute->gatherMiddleware() ?: null,
62
                        'parameters' => $tokens ?: null,
63
                        ]
64
                    );
65
66
                    $agent = app('tracking.statistics.agent')->firstOrCreate(
67
                        [
68
                        'name' => $agent->getUserAgent(),
69
                        'kind' => $kind,
70
                        'family' => $UAParser->ua->family,
71
                        'version' => $UAParser->ua->toVersion(),
72
                        ]
73
                    );
74
75
                    $device = app('tracking.statistics.device')->firstOrCreate(
76
                        [
77
                        'family' => $UAParser->device->family,
78
                        'model' => $UAParser->device->model,
79
                        'brand' => $UAParser->device->brand,
80
                        ]
81
                    );
82
83
                    $platform = app('tracking.statistics.platform')->firstOrCreate(
84
                        [
85
                        'family' => $UAParser->os->family,
86
                        'version' => $UAParser->os->toVersion(),
87
                        ]
88
                    );
89
90
                    $path = app('tracking.statistics.path')->firstOrCreate(
91
                        [
92
                        'host' => $laravelRequest->getHost(),
93
                        'path' => $laravelRequest->decodedPath(),
94
                        'method' => $laravelRequest->getMethod(),
95
                        'locale' => $laravelRequest->route('locale') ?? app()->getLocale(),
96
                        ], [
97
                        'accessarea' => $laravelRequest->get('accessarea'),
98
                        'parameters' => $laravelRoute->parameters() ?: null,
99
                        ]
100
                    );
101
102
                    $geoip = app('tracking.statistics.geoip')->firstOrCreate(
103
                        [
104
                        'client_ip' => $ip = $laravelRequest->getClientIp(),
105
                        'latitude' => geoip($ip)->getAttribute('lat'),
0 ignored issues
show
Bug introduced by
The method getAttribute does only exist in Torann\GeoIP\Location, but not in Torann\GeoIP\GeoIP.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
106
                        'longitude' => geoip($ip)->getAttribute('lon'),
107
                        ], [
108
                        'client_ips' => $laravelRequest->getClientIps() ?: null,
109
                        'country_code' => mb_strtoupper(geoip($ip)->getAttribute('iso_code')),
110
                        'is_from_trusted_proxy' => $laravelRequest->isFromTrustedProxy(),
111
                        'division_code' => geoip($ip)->getAttribute('state'),
112
                        'postal_code' => geoip($ip)->getAttribute('postal_code'),
113
                        'timezone' => geoip($ip)->getAttribute('timezone'),
114
                        'city' => geoip($ip)->getAttribute('city'),
115
                        ]
116
                    );
117
118
                    $requestDetails = [
119
                        'route_id' => $route->getKey(),
120
                        'agent_id' => $agent->getKey(),
121
                        'device_id' => $device->getKey(),
122
                        'platform_id' => $platform->getKey(),
123
                        'path_id' => $path->getKey(),
124
                        'geoip_id' => $geoip->getKey(),
125
                        'user_id' => $item['user_id'],
126
                        'user_type' => $item['user_type'],
127
                        'session_id' => $item['session_id'],
128
                        'status_code' => $item['status_code'],
129
                        'referer' => $laravelRequest->header('referer') ?: $laravelRequest->get('utm_source'),
130
                        'protocol_version' => $laravelRequest->getProtocolVersion(),
131
                        'language' => $laravelRequest->getPreferredLanguage(),
132
                        'is_no_cache' => $laravelRequest->isNoCache(),
133
                        'wants_json' => $laravelRequest->wantsJson(),
134
                        'is_secure' => $laravelRequest->isSecure(),
135
                        'is_json' => $laravelRequest->isJson(),
136
                        'is_ajax' => $laravelRequest->ajax(),
137
                        'is_pjax' => $laravelRequest->pjax(),
138
                        'created_at' => $item['created_at'],
139
                    ];
140
141
                    app('tracking.statistics.request')->create($requestDetails);
142
                    $item->delete();
143
                } catch (Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
144
                }
145
            }
146
        );
147
    }
148
}
149