Completed
Push — master ( b0f401...90606c )
by Mikhail
01:11
created

Authentication   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 71
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 71
ccs 27
cts 27
cp 1
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A generateContentHash() 0 4 1
A generateSign() 0 4 1
A __invoke() 0 23 3
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 $subaccountId;
20
21
    /**
22
     * Authentication constructor.
23
     * @param string $key
24
     * @param string $secret
25
     * @param string $subaccountId
26
     */
27 21
    public function __construct(string $key, string $secret, ?string $subaccountId = null)
28
    {
29 21
        $this->key = $key;
30 21
        $this->secret = $secret;
31 21
        $this->subaccountId = $subaccountId;
32 21
    }
33
34
    /**
35
     * @param callable $next
36
     * @return Closure
37
     */
38 19
    public function __invoke(callable $next)
39
    {
40 19
        return function (RequestInterface $request, array $options = []) use ($next) {
41 19
            $timestamp = round(microtime(true) * 1000);
42 19
            $contentHash = $this->generateContentHash($request->getBody()->__toString());
43
            $pre_sign = $timestamp .
44 19
                $request->getUri()->__toString() .
45 19
                $request->getMethod() .
46 19
                $contentHash .
47 19
                $this->subaccountId;
48 19
            $sign = $this->generateSign($pre_sign);
49
            $newHeaders = [
50 19
                'Api-Key' => $this->key,
51 19
                'Api-Timestamp' => $timestamp,
52 19
                'Api-Content-Hash' => $contentHash,
53 19
                'Api-Signature' => $sign
54
            ];
55 19
            foreach ($newHeaders as $key => $value) $request = $request->withAddedHeader($key, $value);
56 19
            if (!is_null($this->subaccountId)) $request = $request->withAddedHeader('Api-Subaccount-Id', $this->subaccountId);
57
58 19
            return $next($request, $options);
59 19
        };
60
    }
61
62
    /**
63
     * @param string $content
64
     * @return string
65
     */
66 19
    private function generateContentHash(string $content): string
67
    {
68 19
        return hash('sha512', $content);
69
    }
70
71
    /**
72
     * @param string $preSign
73
     * @return string
74
     */
75 19
    private function generateSign(string $preSign): string
76
    {
77 19
        return hash_hmac('sha512', $preSign, $this->secret);
78
    }
79
80
}