CrunchStatistics::handle()   C
last analyzed

Complexity

Conditions 13
Paths 1

Size

Total Lines 103

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
nc 1
nop 0
dl 0
loc 103
rs 5.2933
c 0
b 0
f 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
3
declare(strict_types=1);
4
5
namespace Rinvex\Statistics\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;
21
    use InteractsWithQueue;
22
    use Queueable;
23
    use SerializesModels;
24
25
    /**
26
     * Execute the job.
27
     *
28
     * @return void
29
     */
30
    public function handle(): void
31
    {
32
        app('rinvex.statistics.datum')->each(function ($item) {
33
            try {
34
                $symfonyRequest = SymfonyRequest::create($item['uri'], $item['server']['REQUEST_METHOD'], $item['input'] ?? [], [], [], $item['server']);
35
                $symfonyRequest->overrideGlobals();
36
37
                LaravelRequest::enableHttpMethodParameterOverride();
38
                $laravelRequest = LaravelRequest::createFromBase($symfonyRequest);
39
                $laravelRoute = app('router')->getRoutes()->match($laravelRequest);
40
                $laravelRequest->setRouteResolver(function () use ($laravelRoute) {
41
                    return $laravelRoute;
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(function ($item) use (&$tokens) {
50
                    return ($item = collect($item)) && $item->contains('variable') ? $tokens[$item[3]] = $item[2] : null;
51
                });
52
53
                $route = app('rinvex.statistics.route')->firstOrCreate([
54
                    'name' => $laravelRoute->getName(),
55
                ], [
56
                    'path' => $laravelRoute->uri(),
57
                    'action' => $laravelRoute->getActionName(),
58
                    'middleware' => $laravelRoute->gatherMiddleware() ?: null,
59
                    'parameters' => $tokens ?: null,
60
                ]);
61
62
                $agent = app('rinvex.statistics.agent')->firstOrCreate([
63
                    'name' => $agent->getUserAgent(),
64
                    'kind' => $kind,
65
                    'family' => $UAParser->ua->family,
66
                    'version' => $UAParser->ua->toVersion(),
67
                ]);
68
69
                $device = app('rinvex.statistics.device')->firstOrCreate([
70
                    'family' => $UAParser->device->family,
71
                    'model' => $UAParser->device->model,
72
                    'brand' => $UAParser->device->brand,
73
                ]);
74
75
                $platform = app('rinvex.statistics.platform')->firstOrCreate([
76
                    'family' => $UAParser->os->family,
77
                    'version' => $UAParser->os->toVersion(),
78
                ]);
79
80
                $path = app('rinvex.statistics.path')->firstOrCreate([
81
                    'host' => $laravelRequest->getHost(),
82
                    'path' => $laravelRequest->decodedPath(),
83
                    'method' => $laravelRequest->getMethod(),
84
                    'locale' => $laravelRequest->route('locale') ?? app()->getLocale(),
85
                ], [
86
                    'accessarea' => $laravelRequest->get('accessarea'),
87
                    'parameters' => $laravelRoute->parameters() ?: null,
88
                ]);
89
90
                $geoip = app('rinvex.statistics.geoip')->firstOrCreate([
91
                    'client_ip' => $ip = $laravelRequest->getClientIp(),
92
                    '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...
93
                    'longitude' => geoip($ip)->getAttribute('lon'),
94
                ], [
95
                    'client_ips' => $laravelRequest->getClientIps() ?: null,
96
                    'country_code' => mb_strtoupper(geoip($ip)->getAttribute('iso_code')),
97
                    'is_from_trusted_proxy' => $laravelRequest->isFromTrustedProxy(),
98
                    'division_code' => geoip($ip)->getAttribute('state'),
99
                    'postal_code' => geoip($ip)->getAttribute('postal_code'),
100
                    'timezone' => geoip($ip)->getAttribute('timezone'),
101
                    'city' => geoip($ip)->getAttribute('city'),
102
                ]);
103
104
                $requestDetails = [
105
                    'route_id' => $route->getKey(),
106
                    'agent_id' => $agent->getKey(),
107
                    'device_id' => $device->getKey(),
108
                    'platform_id' => $platform->getKey(),
109
                    'path_id' => $path->getKey(),
110
                    'geoip_id' => $geoip->getKey(),
111
                    'user_id' => $item['user_id'],
112
                    'user_type' => $item['user_type'],
113
                    'session_id' => $item['session_id'],
114
                    'status_code' => $item['status_code'],
115
                    'referer' => $laravelRequest->header('referer') ?: $laravelRequest->get('utm_source'),
116
                    'protocol_version' => $laravelRequest->getProtocolVersion(),
117
                    'language' => $laravelRequest->getPreferredLanguage(),
118
                    'is_no_cache' => $laravelRequest->isNoCache(),
119
                    'wants_json' => $laravelRequest->wantsJson(),
120
                    'is_secure' => $laravelRequest->isSecure(),
121
                    'is_json' => $laravelRequest->isJson(),
122
                    'is_ajax' => $laravelRequest->ajax(),
123
                    'is_pjax' => $laravelRequest->pjax(),
124
                    'created_at' => $item['created_at'],
125
                ];
126
127
                app('rinvex.statistics.request')->create($requestDetails);
128
                $item->delete();
129
            } catch (Exception $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
130
            }
131
        });
132
    }
133
}
134