Envelope::setRequest()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DanBettles\Defence;
6
7
use Symfony\Component\HttpFoundation\Request;
8
use Psr\Log\LoggerAwareInterface;
9
use Psr\Log\LoggerInterface;
10
11
/**
12
 * An `Envelope` object is passed down the filter chain and then, if the request was deemed suspicious, into the handler.
13
 */
14
class Envelope implements LoggerAwareInterface
15
{
16
    /** @var Request */
17
    private $request;
18
19
    /** @var LoggerInterface */
20
    private $logger;
21
22 650
    public function __construct(Request $request, LoggerInterface $logger)
23
    {
24 650
        $this->setRequest($request);
25 650
        $this->setLogger($logger);
26
    }
27
28 650
    private function setRequest(Request $request): self
29
    {
30 650
        $this->request = $request;
31
32 650
        return $this;
33
    }
34
35 647
    public function getRequest(): Request
36
    {
37 647
        return $this->request;
38
    }
39
40
    /**
41
     * @override
42
     */
43 650
    public function setLogger(LoggerInterface $logger): void
44
    {
45 650
        $this->logger = $logger;
46
    }
47
48 222
    public function getLogger(): LoggerInterface
49
    {
50 222
        return $this->logger;
51
    }
52
53
    /**
54
     * Adds a log entry, containing some useful information taken from the request, to the logger.
55
     */
56 220
    public function addLogEntry(string $level, string $message): void
57
    {
58 220
        $context = [
59 220
            'host_name' => gethostname(),
60 220
            'request_method' => $this->getRequest()->getRealMethod(),
61 220
            'uri' => $this->getRequest()->getUri(),
62 220
        ];
63
64 220
        if (Request::METHOD_POST === $this->getRequest()->getRealMethod()) {
65 21
            $context['parameters'] = $this->getRequest()->request->all();
66
        }
67
68 220
        if ($this->getRequest()->headers->has('User-Agent')) {
69 11
            $context['user_agent'] = $this->getRequest()->headers->get('User-Agent');
70
        }
71
72 220
        if ($this->getRequest()->headers->has('referer')) {
73 1
            $context['referer'] = $this->getRequest()->headers->get('referer');
74
        }
75
76 220
        $this->getLogger()->log($level, $message, $context);
77
    }
78
}
79