Completed
Push — master ( c44990...b4ec9a )
by Mikhail
01:07
created

Authentication   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 2

Importance

Changes 0
Metric Value
wmc 4
lcom 2
cbo 2
dl 0
loc 63
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A __invoke() 0 11 1
A addAuthQueryParams() 0 9 1
A generateSign() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace R3bers\BittrexApi\Middleware;
6
7
use Closure;
8
use Psr\Http\Message\RequestInterface;
9
10
class Authentication
11
{
12
    /** @var string */
13
    private $key;
14
15
    /** @var string */
16
    private $secret;
17
18
    /** @var string */
19
    private $nonce;
20
21
    /**
22
     * Authentication constructor.
23
     * @param string $key
24
     * @param string $secret
25
     * @param string $nonce
26
     */
27
    public function __construct(string $key, string $secret, string $nonce)
28
    {
29
        $this->key = $key;
30
        $this->secret = $secret;
31
        $this->nonce = $nonce;
32
    }
33
34
    /**
35
     * @param callable $next
36
     * @return Closure
37
     */
38
    public function __invoke(callable $next)
39
    {
40
        return function (RequestInterface $request, array $options = []) use ($next) {
41
42
            $request = $this->addAuthQueryParams($request);
43
            $sign = $this->generateSign($request->getUri()->__toString());
44
            $request = $request->withAddedHeader('apisign', $sign);
45
46
            return $next($request, $options);
47
        };
48
    }
49
50
    /**
51
     * @param RequestInterface $request
52
     * @return RequestInterface
53
     */
54
    private function addAuthQueryParams(RequestInterface $request): RequestInterface
55
    {
56
        parse_str($request->getUri()->getQuery(), $params);
57
        $params['nonce'] = $this->nonce;
58
        $params['apikey'] = $this->key;
59
        $uri = $request->getUri()->withQuery(http_build_query($params));
60
61
        return $request->withUri($uri);
62
    }
63
64
    /**
65
     * @param string $uri
66
     * @return string
67
     */
68
    private function generateSign(string $uri): string
69
    {
70
        return hash_hmac('sha512', $uri, $this->secret);
71
    }
72
}
73