Completed
Push — master ( 954646...a87a0a )
by Guillaume
9s
created

JwtManager   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 84
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 5
dl 0
loc 84
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 19 1
A getJwtToken() 0 14 1
A getDefaultHeaders() 0 8 1
1
<?php
2
3
namespace Eljam\GuzzleJwt\Manager;
4
5
use Eljam\GuzzleJwt\JwtToken;
6
use Eljam\GuzzleJwt\Strategy\Auth\AuthStrategyInterface;
7
use GuzzleHttp\ClientInterface;
8
use GuzzleHttp\request;
9
use Symfony\Component\OptionsResolver\OptionsResolver;
10
11
/**
12
 * @author Guillaume Cavana <[email protected]>
13
 */
14
class JwtManager
15
{
16
    /**
17
     * $client Guzzle Client.
18
     *
19
     * @var ClientInterface
20
     */
21
    protected $client;
22
23
    /**
24
     * $auth Authentication Strategy.
25
     *
26
     * @var AuthStrategyInterface
27
     */
28
    protected $auth;
29
30
    /**
31
     * $options.
32
     *
33
     * @var array
34
     */
35
    protected $options;
36
37
    /**
38
     * Constructor.
39
     *
40
     * @param ClientInterface       $client
41
     * @param AuthStrategyInterface $auth
42
     * @param array                 $options
43
     */
44
    public function __construct(
45
        ClientInterface $client,
46
        AuthStrategyInterface $auth,
47
        array $options = []
48
    ) {
49
        $this->client = $client;
50
        $this->auth = $auth;
51
52
        $resolver = new OptionsResolver();
53
        $resolver->setDefaults([
54
            'token_url' => '/token',
55
            'timeout' => 1,
56
            'token_key' => 'token',
57
        ]);
58
59
        $resolver->setRequired(['token_url', 'timeout']);
60
61
        $this->options = $resolver->resolve($options);
62
    }
63
64
    /**
65
     * getToken.
66
     *
67
     * @return JwtToken
68
     */
69
    public function getJwtToken()
70
    {
71
        $url = $this->options['token_url'];
72
73
        $requestOptions = array_merge(
74
            $this->getDefaultHeaders(),
75
            $this->auth->getRequestOptions()
76
        );
77
78
        $response = $this->client->request('POST', $url, $requestOptions);
79
        $body = json_decode($response->getBody(), true);
80
81
        return new JwtToken($body[$this->options['token_key']]);
82
    }
83
84
    /**
85
     * getHeaders. Return defaults header.
86
     *
87
     * @return array
88
     */
89
    private function getDefaultHeaders()
90
    {
91
        return [
92
            \GuzzleHttp\RequestOptions::HEADERS => [
93
                'timeout' => $this->options['timeout'],
94
            ],
95
        ];
96
    }
97
}
98