Passed
Push — master ( afa595...3d30f2 )
by Marcel
08:58
created

RequestProcessor::getUserAgent()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 6
rs 10
1
<?php
2
3
namespace App\Monolog;
4
5
use Monolog\Processor\ProcessorInterface;
6
use Symfony\Component\HttpFoundation\RequestStack;
7
8
class RequestProcessor implements ProcessorInterface {
9
10
    private ?string $userAgent = null;
11
    private ?string $url = null;
12
    private ?string $referer = null;
13
14
    public function __construct(private RequestStack $requestStack)
15
    {
16
    }
17
18
    /**
19
     * @inheritDoc
20
     */
21
    public function __invoke(array $records): array {
22
        $records['extra']['useragent'] = $this->getUserAgent();
23
        $records['extra']['url'] = $this->getUrl();
24
        $records['extra']['referer'] = $this->getXhrBaseUrl();
25
26
        return $records;
27
    }
28
29
    private function getUserAgent(): ?string {
30
        if($this->userAgent === null && $this->requestStack->getMainRequest() !== null) {
31
            $this->userAgent = $this->requestStack->getMainRequest()->headers->get('User-Agent');
32
        }
33
34
        return $this->userAgent;
35
    }
36
37
    private function getUrl(): ?string {
38
        if($this->url === null && $this->requestStack->getMainRequest() !== null) {
39
            $this->url = $this->requestStack->getMainRequest()->getRequestUri();
40
        }
41
42
        return $this->url;
43
    }
44
45
    private function getXhrBaseUrl(): ?string {
46
        if($this->referer === null && $this->requestStack->getMainRequest() !== null) {
47
            $this->referer = $this->requestStack->getMainRequest()->headers->get('Referer');
48
49
            // Check if referer is from same host
50
            if(!empty($this->referer)) {
51
                $host = parse_url($this->referer, PHP_URL_HOST);
52
53
                if($host !== $this->requestStack->getMainRequest()->getHost()) {
54
                    $this->referer = null;
55
                }
56
            }
57
        }
58
59
        return $this->referer;
60
    }
61
}