UserDataAppending::onKernelRequest()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.6666
c 0
b 0
f 0
ccs 0
cts 7
cp 0
cc 3
nc 3
nop 0
crap 12
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Dziki\MonologSentryBundle\SubscribedProcessor;
6
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
use Symfony\Component\HttpKernel\KernelEvents;
9
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
10
use Symfony\Component\Security\Core\User\UserInterface;
11
12
class UserDataAppending implements EventSubscriberInterface
13
{
14
    /** @var string */
15
    private $user;
16
    /** @var TokenStorageInterface */
17
    private $tokenStorage;
18
19
    public function __construct(
20
        TokenStorageInterface $tokenStorage
21
    ) {
22
        $this->tokenStorage = $tokenStorage;
23
    }
24
25 1
    public static function getSubscribedEvents(): array
26
    {
27
        return [
28 1
            KernelEvents::REQUEST => ['onKernelRequest', 7],
29
        ];
30
    }
31
32
    public function __invoke(array $record)
33
    {
34
        if ($this->user) {
35
            $record['context']['user'] = [
36
                'username' => $this->user,
37
            ];
38
        }
39
40
        return $record;
41
    }
42
43
    public function onKernelRequest(): void
44
    {
45
        $token = $this->tokenStorage->getToken();
46
47
        if (null === $token) {
48
            return;
49
        }
50
51
        $user = $token->getUser();
52
53
        if ($user instanceof UserInterface) {
54
            $this->user = $user->getUsername();
55
56
            return;
57
        }
58
59
        $this->user = (string) $user;
60
    }
61
}
62