Authentication   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
eloc 18
c 1
b 0
f 0
dl 0
loc 61
ccs 19
cts 19
cp 1
rs 10

4 Methods

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