Passed
Push — master ( c4db50...f768fd )
by Michał
02:54
created

UserDataAppending::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 UserInterface */
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',
29
        ];
30
    }
31
32
    public function __invoke(array $record)
33
    {
34
        $record['context']['user'] = [
35
            'username' => $this->user ? $this->user->getUsername() : 'Anonymous',
36
        ];
37
38
        return $record;
39
    }
40
41
    public function onKernelRequest(): void
42
    {
43
        $token = $this->tokenStorage->getToken();
44
45
        if (null === $token) {
46
            return;
47
        }
48
49
        if (!\is_object($user = $token->getUser())) {
50
            // e.g. anonymous authentication
51
            return;
52
        }
53
54
        $this->user = $user;
55
    }
56
}
57