Passed
Push — master ( 319fcb...7a107a )
by Rafael
04:41
created

JWTContext::setKernel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 3
c 0
b 0
f 0
ccs 0
cts 3
cp 0
rs 10
cc 1
eloc 1
nc 1
nop 1
crap 2
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\Behat\Context;
12
13
use Behat\Behat\Context\Context;
14
use Behat\Behat\Hook\Scope\BeforeStepScope;
15
use Behat\Symfony2Extension\Context\KernelAwareContext;
16
use Symfony\Component\HttpKernel\Kernel;
17
use Symfony\Component\HttpKernel\KernelInterface;
18
use Ynlo\GraphQLBundle\Behat\Authentication\JWT\TokenGeneratorInterface;
19
use Ynlo\GraphQLBundle\Behat\Authentication\UserResolverInterface;
20
use Ynlo\GraphQLBundle\Behat\Client\ClientAwareInterface;
21
use Ynlo\GraphQLBundle\Behat\Client\ClientAwareTrait;
22
use Ynlo\GraphQLBundle\Behat\GraphQLApiExtension;
23
24
/**
25
 * JWT Context
26
 */
27
final class JWTContext implements Context, KernelAwareContext, ClientAwareInterface
28
{
29
    use ClientAwareTrait;
30
31
    /**
32
     * @var Kernel
33
     */
34
    protected $kernel;
35
36
    private static $tokens = [];
37
38
    protected $token;
39
40
    /**
41
     * Sets Kernel instance.
42
     *
43
     * @param KernelInterface $kernel
44
     */
45
    public function setKernel(KernelInterface $kernel)
46
    {
47
        $this->kernel = $kernel;
0 ignored issues
show
Documentation Bug introduced by
$kernel is of type Symfony\Component\HttpKernel\KernelInterface, but the property $kernel was declared to be of type Symfony\Component\HttpKernel\Kernel. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
48
    }
49
50
    /**
51
     * @BeforeScenario
52
     */
53
    public function beforeScenario()
54
    {
55
        $this->token = null;
56
    }
57
58
    /**
59
     * @BeforeStep
60
     */
61
    public function beforeStep(BeforeStepScope $scope)
62
    {
63
        $config = GraphQLApiExtension::getConfig();
64
        if (!isset($config['jwt']['users'])) {
65
            return;
66
        }
67
68
        if ($this->token) {
69
            $this->setToken($this->token);
70
71
            return;
72
        }
73
74
        foreach ($config['jwt']['users'] as $username) {
75
            if (\in_array($username, $scope->getFeature()->getTags())) {
76
                if (isset(self::$tokens[$username])) {
77
                    $this->token = self::$tokens[$username];
78
                    $this->setToken($this->token);
79
                    break;
80
                }
81
82
                $resolverClass = $config['jwt']['user_resolver'];
83
                $tokenGeneratorClass = $config['jwt']['generator'];
84
85
                /** @var UserResolverInterface $resolver */
86
                $resolver = new $resolverClass($this->kernel);
87
                $user = $resolver->findByUsername($username);
88
89
                /** @var TokenGeneratorInterface $tokenGenerator */
90
                $tokenGenerator = new $tokenGeneratorClass($this->kernel);
91
                $this->token = $tokenGenerator->generate($user);
92
93
                if (!$this->token) {
94
                    throw new \RuntimeException('Cant resolve a token using given credentials');
95
                }
96
97
                self::$tokens[$username] = $this->token;
98
                $this->setToken($this->token);
99
                break;
100
            }
101
        }
102
    }
103
104
    protected function setToken($token)
105
    {
106
        $tokenIn = $config['jwt']['token_in'] ?? 'header';
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $config seems to never exist and therefore isset should always be false.
Loading history...
107
        $tokenName = $config['jwt']['token_name'] ?? 'Authorization';
108
        $tokenTemplate = $config['jwt']['token_template'] ?? 'Bearer {token}';
109
110
        if ($token) {
111
            $tokenValue = str_replace('{token}', $token, $tokenTemplate);
112
            switch ($tokenIn) {
113
                case 'header':
114
                    $this->client->setServerParameter(sprintf('HTTP_%s', $tokenName), $tokenValue);
115
                    break;
116
                case 'query':
117
                    $query = http_build_query([$tokenName => $tokenValue], null, '&');
118
                    $this->client->setEndpoint($this->client->getEndpoint().'?'.$query);
119
            }
120
        }
121
    }
122
}
123