Completed
Push — master ( 05297f...b8a6a6 )
by Vragov
03:04
created

AuthenticationPlugin::handleRequest()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 33
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 24
nc 3
nop 3
1
<?php
2
3
namespace SafeCrow\Plugin;
4
5
use Http\Client\Common\Plugin;
6
use Http\Promise\Promise;
7
use Psr\Http\Message\RequestInterface;
8
9
/**
10
 * Class AuthenticationPlugin
11
 * @package SafeCrow\Plugin
12
 */
13
class AuthenticationPlugin implements Plugin
14
{
15
    /**
16
     * @var string
17
     */
18
    protected $key;
19
20
    /**
21
     * @var string
22
     */
23
    protected $secret;
24
25
    /**
26
     * AuthenticationPlugin constructor.
27
     * @param string $key
28
     * @param string $secret
29
     */
30
    public function __construct(string $key, string $secret)
31
    {
32
        $this->key = $key;
33
        $this->secret = $secret;
34
    }
35
36
    /**
37
     * @param RequestInterface $request
38
     * @param callable         $next
39
     * @param callable         $first
40
     * @return Promise
41
     */
42
    public function handleRequest(RequestInterface $request, callable $next, callable $first): Promise
43
    {
44
        switch ($request->getMethod()) {
45
            case 'POST':
46
                $data = sprintf(
47
                    '%s%s%s%s',
48
                    $this->key,
49
                    'POST',
50
                    $request->getUri()->getPath(),
51
                    (string) $request->getBody()
52
                );
53
                break;
54
            case 'GET':
55
                $data = sprintf(
56
                    '%s%s%s%s',
57
                    $this->key,
58
                    'GET',
59
                    $request->getUri()->getPath(),
60
                    $request->getUri()->getQuery() ? '?'.$request->getUri()->getQuery() : null
61
                );
62
                break;
63
            default:
64
                throw new \LogicException('Invalid Method');
65
        }
66
67
        $password = hash_hmac('sha256', $data, $this->secret);
68
69
        $header = sprintf('Basic %s', base64_encode(sprintf('%s:%s', $this->key, $password)));
70
71
        $request = $request->withHeader('Authorization', $header);
72
73
        return $next($request);
74
    }
75
}
76