Completed
Pull Request — master (#13)
by Rafael
06:46
created

SubscriptionsRequestMiddleware   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 32
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
eloc 14
dl 0
loc 32
ccs 0
cts 18
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A processRequest() 0 15 5
1
<?php
2
/*******************************************************************************
3
 *  This file is part of the GraphQL Bundle package.
4
 *
5
 *  (c) YnloUltratech <[email protected]>
6
 *
7
 *  For the full copyright and license information, please view the LICENSE
8
 *  file that was distributed with this source code.
9
 ******************************************************************************/
10
11
namespace Ynlo\GraphQLBundle\Request;
12
13
use Lcobucci\JWT\Parser;
14
use Lcobucci\JWT\Signer\Hmac\Sha256;
15
use Symfony\Component\HttpFoundation\Request;
16
use Ynlo\GraphQLBundle\Subscription\SubscriptionRequest;
17
18
/**
19
 * This middleware listen for internal subscriptions requests to set this arguments in the query.
20
 *
21
 * NOTE: subscriptions requests are internal requests send by a subscription consumer in order to
22
 * emulate a request like a final user but when a subscription is dispatched.
23
 */
24
class SubscriptionsRequestMiddleware implements RequestMiddlewareInterface
25
{
26
    protected $secret;
27
28
    /**
29
     * SubscriptionsRequestMiddleware constructor.
30
     *
31
     * @param string $secret
32
     */
33
    public function __construct($secret)
34
    {
35
        $this->secret = $secret;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function processRequest(Request $request, ExecuteQuery $query): void
42
    {
43
        $content = $request->getContent();
44
        if ($content
45
            && $request->headers->has('Subscription')
46
            && $subscriptionJWT = $request->headers->get('Subscription')) {
47
            $token = (new Parser())->parse($subscriptionJWT);
48
            if (!$token->verify(new Sha256(), $this->secret)) {
49
                throw new \RuntimeException('Invalid subscription signature');
50
            }
51
52
            $query->setSubscriptionRequest(
53
                new SubscriptionRequest(
54
                    $token->getClaim('jti'),
55
                    unserialize($token->getClaim('data'), [true])
56
                )
57
            );
58
        }
59
    }
60
}
61