Completed
Pull Request — master (#4)
by Ruben
03:24
created

TokenSubscriber   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 15%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 52
ccs 3
cts 20
cp 0.15
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getEvents() 0 6 1
A onBefore() 0 12 3
A __construct() 0 4 1
1
<?php
2
3
namespace MovingImage\Client\VMPro\Subscriber;
4
5
use GuzzleHttp\Event\BeforeEvent;
6
use GuzzleHttp\Event\RequestEvents;
7
use GuzzleHttp\Event\SubscriberInterface;
8
use MovingImage\Client\VMPro\Manager\TokenManager;
9
use MovingImage\Util\Logging\Traits\LoggerAwareTrait;
10
use Psr\Log\LoggerAwareInterface;
11
12
/**
13
 * Class TokenSubscriber.
14
 *
15
 * @author Ruben Knol <[email protected]>
16
 */
17
class TokenSubscriber implements SubscriberInterface, LoggerAwareInterface
18
{
19
    use LoggerAwareTrait;
20
21
    /**
22
     * @const string
23
     */
24
    const AUTH_BEARER = 'Bearer %s';
25
26
    /**
27
     * @var TokenManager
28
     */
29
    private $tokenManager;
30
31
    /**
32
     * TokenSubscriber constructor.
33
     *
34
     * @param TokenManager $tokenManager
35
     */
36 6
    public function __construct(TokenManager $tokenManager)
37
    {
38 6
        $this->tokenManager = $tokenManager;
39 6
    }
40
41
    /**
42
     * {@inheritdoc}
43
     */
44
    public function getEvents()
45
    {
46
        return [
47
            'before' => ['onBefore', RequestEvents::SIGN_REQUEST],
48
        ];
49
    }
50
51
    /**
52
     * Add the Authorization header to requests.
53
     *
54
     * @param BeforeEvent $event Event received
55
     */
56
    public function onBefore(BeforeEvent $event)
57
    {
58
        $request = $event->getRequest();
59
        $options = $request->getConfig();
60
61
        $videoManagerId = isset($options['videoManagerId']) ? $options['videoManagerId'] : null;
62
        $token = $this->tokenManager->getToken($videoManagerId);
63
64
        if ($token !== null) {
65
            $request->setHeader('Authorization', sprintf(self::AUTH_BEARER, $token));
66
        }
67
    }
68
}
69