Completed
Pull Request — master (#37)
by Thierry
05:33
created

UnsealRequestSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace lepiaf\SapientBundle\EventSubscriber;
5
6
use lepiaf\SapientBundle\Exception\RequestDecodeException;
7
use ParagonIE\ConstantTime\Base64UrlSafe;
8
use ParagonIE\Sapient\CryptographyKeys\SealingSecretKey;
9
use ParagonIE\Sapient\Sapient;
10
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
11
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
12
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
13
use Symfony\Component\HttpKernel\KernelEvents;
14
15
class UnsealRequestSubscriber implements EventSubscriberInterface
16
{
17
    /**
18
     * @var Sapient
19
     */
20
    private $sapient;
21
22
    /**
23
     * @var DiactorosFactory
24
     */
25
    private $diactorosFactory;
26
27
    /**
28
     * @var string
29
     */
30
    private $privateKey;
31
32 2
    public function __construct(Sapient $sapient, DiactorosFactory $diactorosFactory, string $privateKey)
33
    {
34 2
        $this->sapient = $sapient;
35 2
        $this->diactorosFactory = $diactorosFactory;
36 2
        $this->privateKey = $privateKey;
37 2
    }
38
39 1
    public static function getSubscribedEvents()
40
    {
41
        return [
42 1
            KernelEvents::REQUEST => ['unsealRequest', -100],
43
        ];
44
    }
45
46 2
    public function unsealRequest(GetResponseEvent $event): void
47
    {
48 2
        $request = $event->getRequest();
49 2
        $psrRequest = $this->diactorosFactory->createRequest($request);
50
        try {
51 2
            $unsealedPsrRequest = $this->sapient->unsealRequest(
52 2
                $psrRequest,
53 2
                new SealingSecretKey(Base64UrlSafe::decode($this->privateKey))
54
            );
55 1
        } catch (\RangeException $rangeException) {
56
            throw new RequestDecodeException('Request is not sealed. Cannot decode request');
57
        }
58
59 1
        $request->initialize(
60 1
            $request->query->all(),
61 1
            $request->request->all(),
62 1
            $request->attributes->all(),
63 1
            $request->cookies->all(),
64 1
            $request->files->all(),
65 1
            $request->server->all(),
66 1
            (string) $unsealedPsrRequest->getBody()
67
        );
68 1
    }
69
}
70