Completed
Push — master ( 6e5d13...ea7fd5 )
by Freek
03:26 queued 01:53
created

LaravelRequestContext::getRouteParameters()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Facade\Ignition\Context;
4
5
use Illuminate\Http\Request;
6
use Facade\FlareClient\Context\RequestContext;
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
        $user = $this->request->user();
21
22
        if (! $user) {
23
            return [];
24
        }
25
26
        try {
27
            if (method_exists($user, 'toFlare')) {
28
                return $user->toFlare();
29
            }
30
31
            if (method_exists($user, 'toArray')) {
32
                return $user->toArray();
33
            }
34
        } catch (\Throwable $e) {
35
            return [];
36
        }
37
38
        return [];
39
    }
40
41
    public function getRoute(): array
42
    {
43
        $route = $this->request->route();
44
45
        return [
46
            'route' => optional($route)->getName(),
47
            'routeParameters' => $this->getRouteParameters(),
48
            'controllerAction' => optional($route)->getActionName(),
49
            'middleware' => array_values(optional($route)->gatherMiddleware() ?? []),
50
        ];
51
    }
52
53
    protected function getRouteParameters(): array
54
    {
55
        try {
56
            return collect(optional($this->request->route())->parameters ?? [])->toArray();
57
        } catch (\Throwable $e) {
58
            return [];
59
        }
60
    }
61
62
    public function toArray(): array
63
    {
64
        $properties = parent::toArray();
65
66
        $properties['route'] = $this->getRoute();
67
68
        $properties['user'] = $this->getUser();
69
70
        return $properties;
71
    }
72
}
73