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

TokenMiddleware::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.0156

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 3
cts 4
cp 0.75
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 1.0156
1
<?php
2
3
namespace MovingImage\Client\VMPro\Middleware;
4
5
use MovingImage\Client\VMPro\Manager\TokenManager;
6
use MovingImage\Util\Logging\Traits\LoggerAwareTrait;
7
use Psr\Http\Message\RequestInterface;
8
use Psr\Log\LoggerAwareInterface;
9
10
/**
11
 * Class TokenMiddleware.
12
 *
13
 * @author Ruben Knol <[email protected]>
14
 */
15
class TokenMiddleware implements LoggerAwareInterface
16
{
17
    use LoggerAwareTrait;
18
19
    /**
20
     * @const string
21
     */
22
    const AUTH_BEARER = 'Bearer %s';
23
24
    /**
25
     * @var TokenManager
26
     */
27
    private $tokenManager;
28
29
    /**
30
     * TokenMiddleware constructor.
31
     *
32
     * @param TokenManager $tokenManager
33
     */
34 6
    public function __construct(TokenManager $tokenManager)
35
    {
36 6
        $this->tokenManager = $tokenManager;
37 6
    }
38
39
    /**
40
     * Middleware invocation method that actually adds the bearer
41
     * token to the HTTP request.
42
     *
43
     * @param callable $handler
44
     *
45
     * @return \Closure
46
     */
47
    public function __invoke(callable $handler)
48
    {
49
        return function (
50
            RequestInterface $request,
51
            array $options
52
        ) use ($handler) {
53
            $videoManagerId = isset($options['videoManagerId']) ? $options['videoManagerId'] : null;
54
            $token = $this->tokenManager->getToken($videoManagerId);
55
56
            return $handler($request->withHeader(
57
                'Authorization',
58
                sprintf(self::AUTH_BEARER, $token)
59
            ), $options);
60
        };
61
    }
62
}
63