Completed
Push — master ( ddaf69...154218 )
by Tarmo
17s queued 13s
created

RequestLogSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * /src/EventSubscriber/RequestLogSubscriber.php
5
 *
6
 * @author TLe, Tarmo Leppänen <[email protected]>
7
 */
8
9
namespace App\EventSubscriber;
10
11
use App\Security\ApiKeyUser;
12
use App\Security\SecurityUser;
13
use App\Security\UserTypeIdentification;
14
use App\Utils\RequestLogger;
15
use Symfony\Component\DependencyInjection\Attribute\Autowire;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpKernel\Event\TerminateEvent;
19
use Throwable;
20
use function array_filter;
21
use function array_values;
22
use function in_array;
23
use function str_contains;
24
use function substr;
25
26
/**
27
 * Class RequestLogSubscriber
28
 *
29
 * @package App\EventSubscriber
30
 * @author TLe, Tarmo Leppänen <[email protected]>
31
 *
32
 * @property array<int, string> $ignoredRoutes
33
 */
34
class RequestLogSubscriber implements EventSubscriberInterface
35
{
36
    /**
37
     * RequestLogSubscriber constructor.
38
     *
39
     * @param array<int, string> $ignoredRoutes
40
     */
41 607
    public function __construct(
42
        private readonly RequestLogger $requestLogger,
43
        private readonly UserTypeIdentification $userService,
44
        #[Autowire('%env(key:REQUEST_LOG_IGNORED_ROUTES:json:file:APPLICATION_CONFIG)%')]
45
        private readonly array $ignoredRoutes,
46
    ) {
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     *
52
     * @return array<string, array<int, string|int>>
53
     */
54 1
    public static function getSubscribedEvents(): array
55
    {
56
        return [
57
            TerminateEvent::class => [
58 1
                'onTerminateEvent',
59
                15,
60
            ],
61
        ];
62
    }
63
64
    /**
65
     * Subscriber method to log every request / response.
66
     *
67
     * @throws Throwable
68
     */
69 607
    public function onTerminateEvent(TerminateEvent $event): void
70
    {
71 607
        $request = $event->getRequest();
72 607
        $path = $request->getPathInfo();
73
74 607
        $filter = static fn (string $route): bool =>
75 545
            str_contains($route, '/*') && str_contains($path, substr($route, 0, -2));
76
77
        // We don't want to log OPTIONS requests, /_profiler* -path, ignored routes and wildcard ignored routes
78 607
        if ($request->getRealMethod() === Request::METHOD_OPTIONS
79 558
            || str_contains($path, '/_profiler')
80 558
            || in_array($path, $this->ignoredRoutes, true)
81 607
            || array_values(array_filter($this->ignoredRoutes, $filter)) !== []
82
        ) {
83 62
            return;
84
        }
85
86 545
        $this->process($event);
87
    }
88
89
    /**
90
     * Method to process current request event.
91
     *
92
     * @throws Throwable
93
     */
94 545
    private function process(TerminateEvent $event): void
95
    {
96 545
        $request = $event->getRequest();
97
98
        // Set needed data to logger and handle actual log
99 545
        $this->requestLogger->setRequest($request);
100 545
        $this->requestLogger->setResponse($event->getResponse());
101
102 545
        $identify = $this->userService->getIdentity();
103
104 545
        if ($identify instanceof SecurityUser) {
105 259
            $this->requestLogger->setUserId($identify->getUserIdentifier());
106 288
        } elseif ($identify instanceof ApiKeyUser) {
0 ignored issues
show
introduced by
$identify is always a sub-type of App\Security\ApiKeyUser.
Loading history...
107 6
            $this->requestLogger->setApiKeyId($identify->getApiKeyIdentifier());
108
        }
109
110 545
        $this->requestLogger->setMainRequest($event->isMainRequest());
111 545
        $this->requestLogger->handle();
112
    }
113
}
114