Authentication   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 6
eloc 26
dl 0
loc 68
ccs 26
cts 26
cp 1
c 4
b 0
f 0
rs 10

4 Methods

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