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

TokenSubscriber::getEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 6
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
crap 2
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