LaravelRequestContext::getUser()   B
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 9
nop 0
dl 0
loc 26
rs 8.8817
c 0
b 0
f 0
1
<?php
2
3
namespace Facade\Ignition\Context;
4
5
use Facade\FlareClient\Context\RequestContext;
6
use Illuminate\Http\Request;
7
8
class LaravelRequestContext extends RequestContext
9
{
10
    /** @var \Illuminate\Http\Request */
11
    protected $request;
12
13
    public function __construct(Request $request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
14
    {
15
        $this->request = $request;
16
    }
17
18
    public function getUser(): array
19
    {
20
        try {
21
            $user = $this->request->user();
22
23
            if (! $user) {
24
                return [];
25
            }
26
        } catch (\Throwable $e) {
27
            return [];
28
        }
29
30
        try {
31
            if (method_exists($user, 'toFlare')) {
32
                return $user->toFlare();
33
            }
34
35
            if (method_exists($user, 'toArray')) {
36
                return $user->toArray();
37
            }
38
        } catch (\Throwable $e) {
39
            return [];
40
        }
41
42
        return [];
43
    }
44
45
    public function getRoute(): array
46
    {
47
        $route = $this->request->route();
48
49
        return [
50
            'route' => optional($route)->getName(),
51
            'routeParameters' => $this->getRouteParameters(),
52
            'controllerAction' => optional($route)->getActionName(),
53
            'middleware' => array_values(optional($route)->gatherMiddleware() ?? []),
54
        ];
55
    }
56
57
    protected function getRouteParameters(): array
58
    {
59
        try {
60
            return collect(optional($this->request->route())->parameters ?? [])->toArray();
61
        } catch (\Throwable $e) {
62
            return [];
63
        }
64
    }
65
66
    public function toArray(): array
67
    {
68
        $properties = parent::toArray();
69
70
        $properties['route'] = $this->getRoute();
71
72
        $properties['user'] = $this->getUser();
73
74
        return $properties;
75
    }
76
}
77